Lecture 3
if statements let a program make decisions.
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.5if ph < 7: print("acid")elif ph == 7: print("neutral")else: print("base")Output
acid
Combine a loop with an if to count or collect only the items that pass a test.
evens = 0for v in [2, 7, 4, 9]: if v % 2 == 0: evens += 1print(evens)Output
2
Two separate if statements are each checked, so both can run. Use elif when only one branch should.
x = 10if x > 5: print("over 5")if x > 8: print("over 8")Output
over 5 over 8
From the advanced notebook — this is what the advanced questions test.
value_if_true if condition else value_if_false picks one of two values in a single line.
x = 7print("even" if x % 2 == 0 else "odd")Output
odd
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']