Logical Operators: or
The second logical operator is or. “If it's Saturday or Sunday, it's the weekend”:
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend")This prints:
It's the weekendA condition joined with or is true if at least one of its parts is true. It's false only if all the parts are false:
True or TrueisTrueTrue or FalseisTrueFalse or TrueisTrueFalse or FalseisFalse
A typical mistake is to shorten the condition the way we speak: day == "Saturday" or "Sunday". Python takes the right part on its own: it's just the text "Sunday", not a comparison. Text that isn't empty counts as true, so the whole condition is always true, even on Monday. Each part needs its own comparison: day == "Saturday" or day == "Sunday".
You can use and and or in one condition. Just as multiplication goes before addition, and goes before or. Use parentheses to group what belongs together, as in math:
day = "Saturday"
temperature = 15
if (day == "Saturday" or day == "Sunday") and temperature > 20:
print("Let's go on a trip")
else:
print("Let's stay at home")This prints:
Let's stay at homeThe part in parentheses is evaluated first: it's Saturday, so it's true. But temperature > 20 is false, and True and False is false. Without the parentheses, Python would first join day == "Sunday" and temperature > 20, and the condition would be true on every Saturday, whatever the weather.
Instructions
A movie theater gives a discount to students and to people aged 65 or more. Write an if statement that prints Discount if is_student is true or age is at least 65. Use or.
New rule: discounts only on Wednesdays. Add and day == "Wednesday" to the end of the condition, put parentheses around the or part, and add an else branch that prints Full price. Today is Monday, so the program prints Full price.
Start programming for free
8/11