Sometimes one condition is not enough. For example, a restaurant gives a discount if 2 or more people come and they have 3000 points or more. You need to check both in a single if.
| Operator | Meaning | True when |
|---|---|---|
| A and B | and | both A and B are true |
| A or B | or | at least one of A, B is true |
and: both conditions
With and the code runs only if every condition holds. If one fails, the whole thing is False:
people = 3
points = 2500
if people >= 2 and points >= 3000:
print("20% off")
else:
print("No 20% discount")No 20% discount
or: one is enough
With or it is enough for one condition to hold. In the same example, the number of people alone is enough:
people = 3
points = 2500
if people >= 2 or points >= 3000:
print("10% off")10% off
or is handy for checking values outside a range, like a cheaper ticket for children up to 12 or seniors from 65:
age = 70
if age <= 12 or age >= 65:
print("30% off")
else:
print("Full price")30% off
and is handy for checking a value inside a range, like a mark between 50 and 100:
mark = 75
if mark >= 50 and mark <= 100:
print("Passed")Passed
and/or: age <= 12 or age >= 65 is right; age <= 12 or >= 65 is a syntax error.Practice
Complete the condition: if people is 2 or more and points is 3000 or more, print 20% off.
people = 3
points = 3500
if ___:
print("20% off")Press Run to see the result. Set people to 2 and points to 3500. If people is 2 or more and points is 3000 or more, print Get an eco bag.
Press Run to see the result. Set age to 15. If age is 12 or less or 65 or more, print 30% off; otherwise print Full price.
Press Run to see the result. Set age to 12 and people to 2. If age is 12 or less and people is 1 or more, print Child fare.
Press Run to see the result. Complete the condition: if the number of people is 10 or more or the total is 10000 or more, print Bonus Gift.
number_of_people = 4
total = 13500
if ___:
print("Bonus Gift")Press Run to see the result. A student joins the competition if their maths mark is 85 or more and their attendance is 90 or more. With math = 88 and attendance = 86, print Accepted or Not accepted.
math = 88 attendance = 86
Press Run to see the result. The school cancels the morning assembly if the temperature is 38 or more or rain is "yes". With temp = 31 and rain = "yes", print No assembly today; otherwise print Assembly at 8:00.
temp = 31 rain = "yes"
Press Run to see the result. Key points
A and Bis true only when both conditions are true.A or Bis true when at least one is true.- Write a full condition on each side:
age <= 12 or age >= 65.