Lab 5
6 October, 2023 - Loops and Dictionaries
Welcome to week 5!
This week contains a number of further exercises on loops and a couple on dictionaries.
The lab session is also a good moment to ask questions about the first assignment, which is due on 10 October. If you prefer to focus on the assignment, it may be wise to do some of these exercises at home.
For a quick refresher on loops, you can refer to lab 4. For loops and dictionaries, you can also refer to the sheets of lecture 3 and lecture 4 on Brightspace.
Recall, in particular:
- you can use
continueto skip an iteration of a loop:for num in list: # skip the loop body for all numbers smaller than 10 if num < 10: continue # rest of the loop body ... - you can use
breakto terminate a loop:while num > 0: # terminate the loop if (the current value of) num is odd if num % 2 == 1: break # rest of the loop body ... returnalso terminates a loop:for num in list: # return the first number smaller than 10 if num < 10: return num # rest of the loop body ...- you can use dictionaries as a data structure to store key-value pairs. Recall the following about dictionaries:
fruitbasket = { "apple":3, "banana":5, "cherry":50 } # initialise a dictionary fruitbasket["apple"] # will give the value 3 corresponding to the key "apple"" fruitbasket["apple"] += 2 # update a value fruitbasket["mango"] = 1 # add a new value del fruitbasket["banana"] # delete a value fruitbasket.get("apple") # will return fruitbasket["apple"], as it exists fruitbasket.get("pear") # will return None, since it doesn't exist fruitbasket.keys() # will return a list of keys, such as ["apple", "banana", "cherry"] fruitbasket.values() # will return a list of values, such as [3, 5, 50] fruitbasket.items() # will return a list of key-value tuples, such as [("apple", 3), ("banana", 5), ("cherry", 50)]
As always, if you have any problems or additional questions, make sure to post them on Brightspace.