Python Booleans – Tutorial with Examples

Booleans are a fundamental data type in any programming language, and Python is no exception. A Boolean represents a binary value, either True or False. In Python, Booleans are used for conditional statements, as well as for representing truth values in general.

Creating Booleans

You can create a Boolean in Python simply by assigning a value of True or False to a variable:

a = True
b = False

You can also create a Boolean from a comparison operation:

x = 5
y = 10

result = x < y
print(result)  # Output: True

In the example above, the result of the comparison x < y is a Boolean value of True.

Boolean Operations

In addition to simple comparisons, you can also perform more complex operations on Booleans using the following operators:

  • and
  • or
  • not

Here’s an example using the and operator:

x = 5
y = 10

result = (x < y) and (x > 0)
print(result)  # Output: True

In the example above, both conditions (x < y) and (x > 0) must be true in order for the overall result to be True.

Here’s an example using the or operator:

x = 5
y = 10

result = (x < y) or (x > 10)
print(result)  # Output: True

In the example above, only one of the conditions must be true in order for the overall result to be True.

Here’s an example using the not operator:

x = 5

result = not (x > 10)
print(result)  # Output: True

In the example above, the not operator inverts the value of the condition, so that a True condition becomes False and vice versa.

Booleans in Conditional Statements

Booleans are commonly used in conditional statements to control the flow of execution in a program. For example:

x = 5
y = 10

if x < y:
    print("x is less than y")
else:
    print("x is greater than or equal to y")

In the example above, the condition x < y is a Boolean that determines whether the code in the if block will be executed or not. If the condition is True, the code in the if block will be executed and the message “x is less than y” will be printed. If the condition is False, the code in the else block will be executed and the message “x is greater than or equal to y” will be printed.

Conclusion

In this article, we’ve explored the basics of Booleans in Python, including how to create them, perform operations on them, and use them in conditional statements. Whether you’re just starting out with Python or you’re a seasoned programmer, understanding the basics of Booleans is an essential part of your journey.

Leave a Reply

Your email address will not be published. Required fields are marked *