Logical Expressions and Comparison Operators
In Python, logical expressions are used to compare values and make decisions based on the result (True or False). These expressions are fundamental when writing if
statements or controlling loops.
What is a Logical Expression?
A logical expression (also called a Boolean expression) is an expression that evaluates to either True
or False
.
5 > 3 # True
10 == 10 # True
4 != 2 # True
7 < 1 # False
Comparison Operators
Operator | Meaning | Example | Result |
---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 3 != 4 |
True |
> |
Greater than | 7 > 2 |
True |
< |
Less than | 1 < 5 |
True |
>= |
Greater than or equal | 8 >= 8 |
True |
<= |
Less than or equal | 6 <= 7 |
True |
These operators help compare numbers, strings, and even lists in some cases.
Combining Conditions: and
, or
, not
You can combine multiple logical expressions using logical operators:
and
Returns True
only if both expressions are True
x = 10
x > 5 and x < 20 # True
x > 5 and x < 9 # False
or
Returns True
if at least one expression is True
.
x = 10
x < 5 or x == 10 # True
x < 5 or x > 20 # False
not
Flips the result of a logical expression.
not True # False
not (5 > 3) # False
Example Use Case
age = 16
if age >= 13 and age <= 19:
print("You're a teenager!")
This checks two conditions with and
. Both must be true for the message to print.
Exercise: Try It Yourself!
- Write expressions for the following and print the result:
- Is 5 equal to 5?
- Is 10 not equal to 9?
- Is 4 greater than or equal to 6?
- Is 7 less than 10 or 15 less than 10?
- Is the opposite of
5 < 2
?
- What will this code output?
x = 12 if x > 10 and x % 2 == 0: print("x is greater than 10 and even")