At least one: or
The operator or combines two conditions into one that is true when at least one of them is true:
day = input("Day: ")
if day == "Saturday" or day == "Sunday":
print("No school today!")
else:
print("Time for school.")
SundayDay: Sunday
No school today!Here are all four combinations:
>>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
FalseOnly False or False gives False. Notice that or is also true when both sides are true: it doesn't mean "one or the other, but not both".
Outside a range
With or, you can check that a number is outside a range, below the lower limit or above the upper one:
number = int(input("Pick a number from 1 to 10: "))
if number < 1 or number > 10:
print("That's not between 1 and 10!")
else:
print(f"You picked {number}.")
12Pick a number from 1 to 10: 12
That's not between 1 and 10!A number can't be below 1 and above 10 at the same time, so number < 1 and number > 10 would never be true. When you check for a value outside a range, the operator is or.
A mistake that hides
Each side of or must be a whole condition, just as with and. This time, though, leaving out part of it doesn't cause an error, which makes the mistake hard to spot:
day = "Monday"
if day == "Saturday" or "Sunday":
print("Weekend!")
Weekend!Python reads the condition as (day == "Saturday") or ("Sunday"). The right side isn't a comparison at all, just a string, and in a condition Python treats any string that isn't empty as true. So the whole condition is always true, whatever the day. The fix is to compare the variable again: day == "Saturday" or day == "Sunday".