Evaluating Expressions
We'll cover the following...
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 > ywhich isFalseas5is not greater than10.It also evaluates
y > 0which isTrueas10is greater than0.True or Falseresults inTrueas only one condition is required to beTruewhen dealing with theoroperator.
not x > y also results in True.
x > yevaluates toFalse(5is not greater than10) and thenotoperator inverts thisFalsetoTrue.
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,
TrueandFalseare not the same as ‘true’ and ‘false’, and their first letter has to be capitalized.