@@ -30,9 +30,9 @@ of keys and values in the form `key1:value1, key2:value2, key3:value3, ...`.
3030Lets take a look at a larger example:
3131
3232
33- mydict = {'name': 'James', 'level':9001}
34- print(mydict[ 'name'] )
35- print(mydict)
33+ mydict = {'name': 'James', 'level':9001}
34+ print(mydict['name'])
35+ print(mydict)
3636
3737
3838Can you see what's happening here? We use square brackets in a similar fashion
@@ -59,9 +59,9 @@ is also possible to assign a value to a key that was not previously in the
5959dictionary using ` = ` , for example:
6060
6161
62- mydict = { } #The empty dictionary
63- mydict[ 'name'] = 'james'
64- print(mydict[ 'name'] )
62+ mydict = { } #The empty dictionary
63+ mydict['name'] = 'james'
64+ print(mydict['name'])
6565
6666
6767For those of you who do maths, we'll note that a dictionary is a actually a
@@ -175,22 +175,22 @@ again. But, because functions have parameters, they enable something much more
175175powerful, the generalisation of code. Suppose we write the following:
176176
177177
178- james = {'name': 'James', 'dob':1993 }
179- sam = {'name': 'Sam', 'dob':1992 }
180- print(james[ 'name'] + ' - ' + str(james[ 'dob'] ))
181- print(sam[ 'name'] + ' - ' + str(sam[ 'dob'] ))
178+ james = {'name': 'James', 'dob':1993 }
179+ sam = {'name': 'Sam', 'dob':1992 }
180+ print(james['name'] + ' - ' + str(james['dob']))
181+ print(sam['name'] + ' - ' + str(sam['dob']))
182182
183183
184184With a function, we can generalise this as follows:
185185
186186
187- def printPerson(person):
188- print(person[ 'name'] + ' - ' + str(person[ 'dob'] ))
187+ def printPerson(person):
188+ print(person['name'] + ' - ' + str(person['dob']))
189189
190- james = {'name': 'James', 'dob':1993 }
191- sam = {'name': 'Sam', 'dob':1992 }
192- printPerson(james)
193- printPerson(sam)
190+ james = {'name': 'James', 'dob':1993 }
191+ sam = {'name': 'Sam', 'dob':1992 }
192+ printPerson(james)
193+ printPerson(sam)
194194
195195
196196Yes, in this example we did write more code, but now suppose we want to actually
@@ -225,12 +225,12 @@ particularly noticeable in functions. It's best to see how this works by
225225examples:
226226
227227
228- def printAndAddOne(number): print(number) return number + 1
228+ def printAndAddOne(number): print(number) return number + 1
229229
230- def main(): x = 1 printAndAddOne(x) x = printAndAddOne(x) print(x)
231- #print(number)
230+ def main(): x = 1 printAndAddOne(x) x = printAndAddOne(x) print(x)
231+ #print(number)
232232
233- main() #print(x)
233+ main() #print(x)
234234
235235
236236This example shows the important behaviour of scoped variables. What do you
0 commit comments