Lesson 11 of 30 · Making Decisions
Logical Operators
Combine conditions in Python with and, or and not. Includes truth tables, range checks and clear examples for beginners.
- 6 min read
- Beginner
- Reviewed
- How to combine conditions with and and or
- How to reverse a condition with not
- How to check that a number is inside a range
More than one condition
Real decisions often depend on several things at once. You can enter a film if you have a ticket and you are old enough. You get a discount if you are a student or over 65.
Python has three logical operators for this: and, or and not.
and: both must be true
and gives True only when both sides are True.
age = 25
has_licence = True
if age >= 18 and has_licence:
print("You can drive.")
else:
print("You cannot drive.")Set has_licence to False, or age to 16, and run it again. If either side fails, the whole condition fails.
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
or: at least one must be true
or gives True when one or both sides are True.
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("It is the weekend!")
else:
print("It is a weekday.")| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
not: the opposite
not flips a boolean. True becomes False, and False becomes True.
is_raining = False
if not is_raining:
print("Let's go for a walk.")
print(not True)
print(not 5 > 3)Combining operators
You can mix the three. Python evaluates not first, then and, then or. Brackets make the order clear, so use them.
age = 70
is_student = False
is_member = True
if (age < 18 or age >= 65 or is_student) and is_member:
print("Discount applied.")
else:
print("Full price.")Checking a range
To test that a number is between two values, you can join two comparisons with and. Python also allows a shorter form that reads like maths.
temperature = 22 print(temperature >= 18 and temperature <= 25) print(18 <= temperature <= 25)
Both lines mean the same thing. The second is easier to read.
Use or to decide the ticket price. Once it passes, try age = 30 with is_student = True, then with False.
age = 15 is_student = False # A ticket is discounted when the customer is under 18 OR is a student. # Print "Discount" or "Full price". # For the values above the output must be exactly: Discount
What is the result of: True and False or True
Summary
andisTrueonly when both sides areTrue.orisTruewhen at least one side isTrue.notreverses a boolean.- Each side of
andandorshould be a complete condition. 18 <= x <= 25checks thatxis within a range.
You can now store data, do calculations, read input and make decisions. Next: making your programs repeat things with loops.
Finished reading? Tick it off to track your progress.