In programming, it’s common to need to compare values with each other. To accomplish this, Python provides six comparison operators, which are listed in the following table:
| Operator | Meaning |
|---|---|
| < | less than |
| <= | less than or equal to |
| > | greater than |
| >= | greater than or equal to |
| == | equal to |
| != | not equal to |
The result of comparing two values is a boolean value: True or False.
a: int = 22
b: int = 404
print(a > b)
# -> FalseIn the case of a > b, the expression is a boolean expression. This refers to an expression that evaluates to a boolean value (True or False).
A variable that stores a boolean value is called a boolean variable. A boolean variable can hold either the value True or the value False. Intern, Python uses the value 1 to represent True and the value 0 to represent False.
x: bool = True
print(int(x))
# -> 1
y: bool = False
print(int(y))
# -> 0In Python, there are three boolean operators (also known as logical operators):
and: ReturnsTrueif both expressions on either side of the operator are true.or: ReturnsTrueif the expression on the left side of the operator or the expression on the right side of the operator is true.not: This operator inverts the value of an expression, as demonstrated in the following code:
>>> x = True
>>> y = not x
>>> print(y)
FalseThe operators can also be combined, as shown in the following example:
>>> a = True
>>> b = False
>>> c = False
>>> a or (b and c)
True
>>> (a and b) or c
False