← All concepts

Lecture 3

if, elif and else

if statements let a program make decisions.

One chain, one branch

Python checks the conditions from the top and runs the first branch that is True; the rest of the chain is skipped. else takes no condition. Indentation decides which lines belong to each branch.

ph = 6.5
if ph < 7:
print("acid")
elif ph == 7:
print("neutral")
else:
print("base")

Output

acid

Decisions inside a loop

Combine a loop with an if to count or collect only the items that pass a test.

evens = 0
for v in [2, 7, 4, 9]:
if v % 2 == 0:
evens += 1
print(evens)

Output

2

Separate ifs are not a chain

Two separate if statements are each checked, so both can run. Use elif when only one branch should.

x = 10
if x > 5:
print("over 5")
if x > 8:
print("over 8")

Output

over 5
over 8

Going further

From the advanced notebook — this is what the advanced questions test.

Conditional expressions

value_if_true if condition else value_if_false picks one of two values in a single line.

x = 7
print("even" if x % 2 == 0 else "odd")

Output

odd

Filtering with comprehensions

An if at the end of a comprehension keeps only the items that pass; an if/else at the front labels every item. not in checks that something is absent.

values = [3, 8, 1, 9]
print([v for v in values if v > 2])
print(["H" if v > 5 else "L" for v in values])
print([b for b in "ANTG" if b not in "N"])

Output

[3, 8, 9]
['L', 'H', 'L', 'H']
['A', 'T', 'G']