# stoive/pythontutorial

### Subversion checkout URL

You can clone with
or
.
Older
100644 224 lines (223 sloc) 13.332 kB
 83567d0 directory restructure stoive authored May 26, 2011 1 2 3 4
5

Your brain still hurting from the last lesson? Never worry, this one will require a little less thought. We're going back to something simple - variables - but a little more in depth.

6

Think about it - variables store one bit of information. They may regurgitate (just not on the carpet...) that information at any point, and their bit of information can be changed at any time. Variables are great at what they do - storing a piece of information that may change over time.

7

But what if you need to store a long list of information, which doesn't change over time? Say, for example, the names of the months of the year. Or maybe a long list of information, that does change over time? Say, for example, the names of all your cats. You might get new cats, some may die, some may become your dinner (we should trade recipies!). What about a phone book? For that you need to do a bit of referencing - you would have a list of names, and attached to each of those names, a phone number. How would you do that?

8
9
10

For these three problems, Python uses three different solutions - Tuples, lists, and dictionaries:

11 12 Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names. 13 Tuples are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year. 14 Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - tare similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book. 15 16
17
18

Tuples are pretty easy to make. You give your tuple a name, then after that the list of values it will carry. For example, the months of the year:

19 20 months = ('January','February','March','April','May','June',\ 21 'July','August','September','October','November',' December') 22 23 24 Note that the '\' thingy at the end of sthurlow.comthe first line carries over that line of code to the next line. It is usefull way of making big lines more readable. 25 Technically you don't have to put those parentheses there (the '(' and ')' thingies) but it stops python from getting things confused. 26 You may have spaces after the commas if you feel it necessary - it doesn't really matter. 27 28

Python then organises those values in a handy, numbered index - starting from zero, in the order that you entered them in. It would be organised like this:

29 30 31 32 33 34 35 0 36 January 37 38 39 1 40 Feb 41 42 43 2 44 Mar 45 46 47 3 48 Apr 49 50 51 4 52 May 53 54 55 5 56 Jun 57 58 59 6 60 Jul 61 62 63 7 64 Aug 65 66 67 8 68 Sep 69 70 71 9 72 Oct 73 74 75 10 76 Nov 77 78 79 11 80 Dec 81 82 83

And that is tuples! Really easy...

84
85
86

Lists are extremely similar to tuples. Lists are modifiable (or 'mutable', as a programmer may say), so their values can be changed. Most of the time we use lists, not tuples, because we want to easily change the values of things if we need to.

87

Lists are defined very similarly to tuples. Say you have FIVE cats, called Tom, Snappy, Kitty, Jessie and Chester. To put them in a list, you would do this:

88 89 cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester'] 90 91

As you see, the code is exactly the same as a tuple, EXCEPT that all the values are put between square brackets, not parentheses. Again, you don't have to have spaces after the comma.

92

You recall values from lists exactly the same as you do with tuples. For example, to print the name of your 3rd cat you would do this:

93 94 print cats[2] 95 96

You can also recall a range of examples, like above, for example - cats[0:2] would recall your 1st and 2nd cats.

97

Where lists come into their own is how they can be modified. To add a value to a list, you use the 'append()' function. Let's say you got a new cat called Catherine. To add her to the list you'd do this:

98 99 cats.append('Catherine') 100 101

That's a little weird, isn't it? I'll explain. That function is in a funny spot - after a period (the '.' kind of period, not otherwise), after the list name. You'll get to see those things more in a later lesson. For the meanwhile, this is the form of the function that adds a new value to a list:

102 103 #add a new value to the end of a list: 104 list_name.append(value-to-add) 105 106 #e.g. to add the number 5038 to the list 'numbers': 107 numbers.append(5038) 108 109

Clears things up? Good!

110

Now to a sad situation - Snappy was shot by a neighbour, and eaten for their dinner (good on 'em!). You need to remove him (or her) from the list. Removing that sorry cat is an easy task, thankfully, so you have to wallow in sadness for as short a time as possible:

111 112 #Remove your 2nd cat, Snappy. Woe is you. 113 del cats[1] 114 115

You've just removed the 2nd cat in your list - poor old Snappy.

116

And with that morbid message, lets move on to...

117
118
119

Ok, so there is more to life than the names of your cats. You need to call your sister, mother, son, the fruit man, and anyone else who needs to know that their favourite cat is dead. For that you need a telephone book.

120

Now, the lists we've used above aren't really suitable for a telephone book. You need to know a number based on someone's name - not the other way around, like what we did with the cats. In the examples of months and cats, we gave the computer a number, and it gave us a name. This time we want to give the computer a name, and it give us a number. For this we need <i>Dictionaries</i>.

121

So how do we make a dictionary? Put away your binding equipment, it isn't that advanced.

122

Remember, dictionaries have keys, and values. In a phone book, you have people's names, then their numbers. See a similarity?

123

When you initially create a dictionary, it is very much like making a tuple or list. Tuples have ( and ) things, lists have [ and ] things. Guess what! dictionaries have { and } things - curly braces. Here is an example below, showing a dictionary with four phone numbers in it:

124 125 #Make the phone book: 126 phonebook = {'Andrew Parson':8806336, \ 127 'Emily Everett':6784346, 'Peter Power':7658344, \ 128 'Lewis Lame':1122345} 129 130

the program would then print Lewis Lame's number onscreen. Notice how instead of identifying the value by a number, like in the cats and months examples, we identify the value, using another value - in this case the person's name.

131

Ok, you've created a new phone book. Now you want to add new numbers to the book. What do you do? A very simple line of code:

132 133 #Add the person 'Gingerbread Man' to the phonebook: 134 135 phonebook['Gingerbread Man'] = 1234567 136 137 # Didn't think I would give you 138 # my real number now, would I? 139 140

All that line is saying is that there is a person called Gingerbread Man in the phone book, and his number is 1234567. In other words - the <i>key</i> is '<u>Gingerbread Man</u>', and the <i>value</i> is <u>1234567</u>.

141

You delete entries in a dictionary just like in a list. Let's say Andrew Parson is your neighbour, and shot your cat. You never want to talk to him again, and therefore don't need his number. Just like in a list, you'd do this:

142 143 del phonebook['Andrew Parson'] 144 145

Again, very easy. the 'del' operator deletes any function, variable, or entry in a list or dictionary (An entry in a dictionary is just a variable with a number or text string as a name. This comes in handy later on.)

146

remember that append function that we used with the list? Well, there are quite a few of those that can be used with dictionaries. Below, I will write you a program, and it will incorporate some of those functions in. It will have comments along the way explaining what it does.

147

Type this program into Python IDLE (you can skip the comments). Experiment as much as you like with it. Type it where you see the lines beginning with >>>

148 149 #A few examples of a dictionary 150 151 #First we define the dictionary 152 #it will have nothing in it this time 153 ages = {} 154 155 #Add a couple of names to the dictionary 156 ages['Sue'] = 23 157 ages['Peter'] = 19 158 ages['Andrew'] = 78 159 ages['Karren'] = 45 160 161 #Use the function has_key() - 162 #This function takes this form: 163 #function_name.has_key(key-name) 164 #It returns TRUE 165 #if the dictionary has key-name in it 166 #but returns FALSE if it doesn't. 167 #Remember - this is how 'if' statements work - 168 #they run if something is true 169 #and they don't when something is false. 170 if ages.has_key('Sue'): 171 print "Sue is in the dictionary. She is", \ 172 ages['Sue'], "years old" 173 174 else: 175 print "Sue is not in the dictionary" 176 177 #Use the function keys() - 178 #This function returns a list 179 #of all the names of the keys. 180 #E.g. 181 print "The following people are in the dictionary:" 182 print ages.keys() 183 184 #You could use this function to 185 #put all the key names in a list: 186 keys = ages.keys() 187 188 #You can also get a list 189 #of all the values in a dictionary. 190 #You use the values() function: 191 print "People are aged the following:", \ 192 ages.values() 193 194 #Put it in a list: 195 values = ages.values() 196 197 #You can sort lists, with the sort() function 198 #It will sort all values in a list 199 #alphabetically, numerically, etc... 200 #You can't sort dictionaries - 201 #they are in no particular order 202 print keys 203 keys.sort() 204 print keys 205 206 print values 207 values.sort() 208 print values 209 210 #You can find the number of entries 211 #with the len() function: 212 print "The dictionary has", \ 213 len(ages), "entries in it" 214 215
216
217

There are many other functions you can use to work with lists and dictionaries - too many to go through right now. We'll leave the lesson at this point - you have learnt enough for one lesson.

218

Thanks to all

219

sthurlow.com

220
221
222
223
Something went wrong with that request. Please try again.