Control structures¶
This notebook introduces the basic control structures of Python. It covers roughly the same ground as this video.
One of the most basic control structures is a for loop. Recall that the function range(1,10) generates a list of integers starting with 1 and ending just before 10. The loop below prints the squares of all the integers in this list. Note that the line starting for has to end with a colon, and the rest of the loop needs to be indented underneath that. The print statement uses an f-string for formatting: see the file formatting.ipynb for more information about how that works.
for i in range(1,10):
j = i * i
print(f'The square of {i} is {j}')
A while loop is similar to a for loop but we continue to run through the loop as long as a specified condition is true. In the example below, we check whether $i^2\lt 42$, and if so, we increment $i$. When we get to $i=7$ we find that $i^2\geq 42$ so we drop out of the loop.
i = 1
while i * i < 42:
print(f'The square of {i} is {i*i}, which is less than 42')
i += 1 # Do not forget to increment i, or the loop will never end!
print(f'The square of {i} is {i*i}, which is >= 42')
Sometimes we want to exit a loop before in naturally ends. For example, if we are searching for something, then it is natural to exit the loop as soon as we have found it. The break statement is used for this. In the example below, we search for an integer square root of 196. (Of course, this method is extremely inefficient and is only given as an illustration.) Note that the if statement also has a colon at the end, and everything controlled by the if statement is indented by a further 4 spaces.
# Example of a break statement to exit a loop early
found = False
for i in range(1000):
if i * i == 196:
found = True
print(f'The square root of 196 is {i}')
break # Exit the loop
if not found:
print('No square root found')
An if statement can have an else clause, and possibly also some elif clauses as in the example below.
# Animal noises using if-elif-else
animal = 'cat'
if animal == 'pig':
print('oink')
elif animal == 'dog':
print('woof')
elif animal == 'cat':
print('meow')
elif animal == 'cow':
print('moo')
else:
print('I do not recognize that animal')
Here is another (better) way to do the above example using a dictionary.
# Animal noises using a dictionary
animal = 'aardvark'
noises = {'pig': 'oink', 'dog': 'woof', 'cat': 'meow', 'cow': 'moo'}
print(noises[animal] if animal in noises else 'I do not recognize that animal')
print(noises.get(animal, 'I do not recognize that animal')) # Same as above, but using get() instead of if-else
I do not recognize that animal I do not recognize that animal