Evaluating Expressions
We often aim to perform a certain task based on whether or not a condition is true.
A key use of booleans in Python is to evaluate expressions. Such expressions often contain boolean operators (e.g., or, and, not) or comparison operators (e.g., <
, ==
, >
, <=
, >=
).
Evaluating expressions
Expressions can be evaluated using either bool()
or directly using operators. For instance, both of these cases will work.
Suppose we have two variables, x
and y
, with the values 5
and 10
, respectively.
x = 5y = 10
Using the bool()
method
The bool()
method is used in the snippet below to compare x
and y
.
Let’s check if they’re equal or not. The expression will result in False
as 5
is not equal to 10
.
x = 5y = 10print(bool(x == y))
Directly using operators
We can achieve the same result by directly using operators as well.
x = 5y = 10print(x == y)
Let’s also experiment with boolean and comparison operators.
Using boolean operators (e.g., and, or, not)
Let's take an example involving the or
operator. The or
operator will result in True
if any of the conditions are true.
x > y or y > 0
results in True
.
The statement first evaluates
x > y
which isFalse
as5
is not greater than10
.It also evaluates
y > 0
which isTrue
as10
is greater than0
.True or False
results inTrue
as only one condition is required to beTrue
when dealing with theor
operator.
not x > y
also results in True.
x > y
evaluates toFalse
(5
is not greater than10
) and thenot
operator inverts thisFalse
toTrue
.
x = 5y = 10print(x > y or y > 0)print(not x > y)
Using comparison operators
The first statement x != y
evaluates to True
as 5
is indeed not equal to 10
. On the other hand, x >= y
evaluates to False
as 5
is not greater than equal to 10
.
x = 5y = 10print(x != y)print(x >= y)
Note: In Python,
True
andFalse
are not the same as ‘true’ and ‘false’, and their first letter has to be capitalized.