Python Boolean expression is an expression that evaluates to produce a result which is a Boolean value. An if statement uses the equal operator == to test if two values are equal and produce (or yield) a Boolean value.
The Boolean values in Python are True
and False
, typically used to control if-statements and while-loops.
Boolean expression Python example
Simple example code that returns a True or False value.
# Is three greater than two?
print(1 > 2)
# Is the number of characters in the string "Hello" equal to one?
print(len("Hello") == 1)
# Is 5 equal to 3 + 2?
print(5 == 3 + 2)
# Is four greater than or equal to nine?
print(2 + 2 >= 10)
# Is seven not equal to twelve?
print(5 != 10)
Output:
Boolean expression in the if else statement
my_number = 24
if my_number % 2 == 0:
print(my_number, "is even.")
else:
print(my_number, "is odd.")
Python Comparison Operators
Mostly Boolean expressions are expressions that use comparison operators.
Operator | Meaning |
x == y | x equals y |
x != y | x does not equal y, x is not equal to y |
x >= y | x is greater than or equal to y |
x <= y | x is less than or equal to y |
A Truth Table for Python Boolean Expressions
Expression 1 | Connector | Expression 2 | Result |
True | and | True | True |
False | and | True | False * |
True | and | False | False |
False | and | False | False * |
True | or | True | True * |
False | or | True | True |
True | or | False | True * |
False | or | False | False |
Do comment if you have any doubts or suggestions on this Python basic topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.