Flow controls: Conditions · 3 / 22 Theory

Compound conditions: and, or, not, in

Many decisions depend on more than one thing at once. Logical operators let you combine conditions into one.

and: both must be true

age = int(input())

if age >= 18 and age < 65:
    print("Working age")

or: one is enough

day = input()

if day == "saturday" or day == "sunday":
    print("Weekend")

Careful: you must repeat the variable in each comparison. day == "saturday" or "sunday" is a classic mistake: it is always true because "sunday" (a non-empty text) counts as True.

not: inverting a condition

n = int(input())
if not n == 0:
    print("Not zero")   # same as n != 0

Chained comparisons

To check a range, Python lets you write it as in maths:

x = int(input())
if 1 <= x <= 10:
    print("Between 1 and 10")   # same as x >= 1 and x <= 10

in: belonging to a set

When you check whether a value is one of several, in is cleaner than many or:

letter = input().lower()

if letter in "aeiou":
    print("It is a vowel")

if letter in ["a", "e", "i", "o", "u"]:   # equivalent with a list
    print("It is a vowel")

This solves the exercise Check vowels without writing five comparisons.

Precedence

not is evaluated before and, and and before or. When in doubt, use parentheses:

a, b, c = True, False, False
print(a or b and c)     # True  (b and c is evaluated first)
print((a or b) and c)   # False

Even numbers with and

A number is even if the remainder of dividing it by 2 is 0. If you want to check two numbers at once:

a = int(input())
b = int(input())
if a % 2 == 0 and b % 2 == 0:
    print("Both are even")

Practice with Check even numbers and The largest of three numbers.