Source
Adapted from my own handwritten and hand-typed notes from Year 1 to Year 3 of my EEE degree
Conditional Expressions
if, elif, else choose which indented block runs:
- the
ifexpression is tested first, and its block runs if it isTrue - if
False, eachelifis tested in turn and the firstTrueone runs - the
elseblock runs only if none of the expressions wereTrue
mark = 72
if mark >= 80:
grade = 'A'
elif mark >= 70:
grade = 'B'
else:
grade = 'C'Indefinite Iteration: while
Repeats its block as long as the expression stays True, testing again before each pass. If the expression never becomes False the result is an infinite loop (force exit with CTRL+C).
n = 1
while n < 100:
n *= 2
print(n) # 128Definite Iteration: for
Loops over an iterable (str, list, tuple, dict, set). Each pass assigns the next item to the loop variable, and the loop exits after the last item.
rainfall = [0, 3.2, 15.6, 0.2]
total = 0
for r in rainfall:
total += r
for name in {'Amy': 8, 'Ben': 4}: # looping over a dict gives its keys
print(name)Nested Statements Example: First n Primes
Conditionals and both loop types can be nested to build complex tasks:
n = 10
prime_list = []
candidate = 2
while len(prime_list) < n: # keep going until n primes found
is_prime = True
for p in prime_list: # test against smaller primes
if candidate % p == 0:
is_prime = False
break
if is_prime:
prime_list.append(candidate)
candidate += 1
print(prime_list) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]Growing a result with append inside a loop is a common pattern, see Python Lists.