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 = 5
y = 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 = 5
y = 10
print(bool(x == y))

Directly using operators

We can achieve the same result by directly using operators as well.

x = 5
y = 10
print(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 is False as 5 is not greater than 10.

  • It also evaluates y > 0 which is True as 10 is greater than 0.

  • True or False results in True as only one condition is required to be True when dealing with the or operator.

not x > y also results in True.

  • x > y evaluates to False (5 is not greater than 10) and the not operator inverts this False to True.

x = 5
y = 10
print(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 = 5
y = 10
print(x != y)
print(x >= y)

Note: In Python, True and False are not the same as ‘true’ and ‘false’, and their first letter has to be capitalized.