Python Logical Operators
A logical operator is a word that joins or flips a true or false value.
Both must be true
The word and needs True on both sides.
print(True and True)
print(True and False)One is enough
The word or needs True on at least one side.
print(True or False)
print(False or False)Flip the answer
The word not turns True into False, and back again.
print(not True)
print(not False)Join two checks
This one check asks if an age sits in the teen range.
age = 14
print(age >= 10 and age < 18)Python can skip a check
When and starts with False, the answer is already False. Python skips the second part, so its print never runs.
print("Before")
False and print("You should not see this")
print("After")Example
age = 12
height = 135
old_enough = age >= 10
tall_enough = height >= 120
can_ride = old_enough and tall_enough
print("Old enough:", old_enough)
print("Tall enough:", tall_enough)
print("Can ride:", can_ride)Key points
- Use and when both parts must be True.
- Use or when at least one part must be True.
- Use not to flip True to False and False to True.
- A logical operator joins two checks or flips one check.
- Python can skip the second part of a check.
- This skipping is called short-circuiting.
In this example, age is 12 and height is 135. Python checks age >= 10 and gets True. It checks height >= 120 and gets True. Both parts are True, so can_ride is True.
Note
and, or and not are lower case words.
True and False start with a capital letter.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does not (True and False) give?