Reading: This class meeting and the next are based on Chapter 5 of Practical Programming.
Gather together values that have common meaning
As a first example, here are scores of 7 judges for the free skating part of the figure skating competition:
scores = [ 59, 61, 63, 63, 68, 64, 58 ]
As a second example, here are the names of the planets in the solar system (including Pluto, for now):
planets = [ 'Mercury', 'Venus', 'Earth', 'Mras', 'Jupiter',
'Saturn', 'Neptune', 'Uranus', 'Pluto' ]
Notes on syntax:
Notice that we made the mistake in typing 'Mras'. How do we fix this? We’ll start by looking at indexing.
The line
>>> print planets[1]
accesses and prints the string at what’s known as index 1 of the list planets. Try it?
Surprised?
Each item / value in the list is associated with a unique index
Indexing in Python (and most other programming languages) starts at 0.
The notation is again to use [ and ] with an integer (non-negative) to indicate which list item.
What is the last index in planets?
Again, are you surprised?
We’ll draw a memory model in class that illustrates the relationship among
Once we know about indexing, changing a value in a list is easy:
>>> planets[3] = 'Mars'
This replaces item 3 of planets with the string 'Mars'
Now we can check the output:
>>> print planets
to make sure we got it right.
If t is a list, then the items are stored at indices from 0 to len(t)-1.
If you try to access indices at len(t) or beyond, you get a run-time error. We’ll take a look and see.
If you access negative indices, interesting things happen:
>>> print planets[-1]
Pluto
More specifically, for any list t, if i is an index from 0 to len(t)-1 then t[i] and t[i-len(t)] are the same spot in the list.
There are many functions (methods) on lists. We can learn all about them using the help command.
This is just like we did for strings and for modules, e.g.
>>> import math
>>> help(math)
>>> help(str)
Interestingly, we can run help in two ways, one
help(list)
gives us the list methods, and the second
help(planets)
tells us that planets is a list before giving us list methods.
First, let’s see some basic functions on the list values.
The basic functions max, sum and min exist for lists as well.
This gives us a simple way to compute the average level in parts per million:
>>> print "Average Scores = %.2f" %(sum(scores) / float(len(scores)))
Average Scores = 62.29
>>> print "Max Score =", max(scores)
Max Score = 68
>>> print "Min Score =", min(scores)
Min Score = 58
Exploring, we will look at what happens when we apply sum, max and min to our list of planet names. Can you explain the result?
We can also sort the values in a list by sorting it. Let’s try the following:
>>> planets = [ 'Mercury', 'Venus', 'Earth', 'Mras', 'Jupiter', \
'Saturn', 'Neptune', 'Uranus', 'Pluto' ]
>>> planets
['Mercury', 'Venus', 'Earth', 'Mras', 'Jupiter', 'Saturn', 'Neptune', 'Uranus', 'Pluto']
>>> planets.sort()
>>> planets
['Earth', 'Jupiter', 'Mercury', 'Mras', 'Neptune', 'Pluto', 'Saturn', 'Uranus', 'Venus']
Note that we did not assign the value returned by sort to a new variable. This is the first function we learnt that modifies the input. Try the following and see what happens:
>>> scores = [ 59, 61, 63, 63, 68, 64, 58 ]
>>> new_scores = scores.sort()
>>> scores
[58, 59, 61, 63, 63, 64, 68]
>>> new_scores
>>>
>>> print scores
[58, 59, 61, 63, 63, 64, 68]
>>> print new_scores
None
>>>
So, the function returns nothing! But, it does change the value of the input list. This is the first such function we have seen.
It does so, because lists are containers and functions can manipulate what is inside containers. They cannot do so for simple types like integer and float.
Let us try to make a list of the crucial things to review before the exam.
Syntax: can you find syntax errors in code?
Correct variable names, assigning a value to a variable
Output: can you compute the output of a piece of code?
Expressions: operator precedence
The distinction between integer and float division
The distinction between division (4/5) and modulo (4%5) operators, and how they work for positive and negative numbers
Remember shorthands: +=, -=, /=, *=.
Functions: defining functions and using them
Distinguish between variables local to functions and variables that are global
Modules: how to import and call functions that are from a specific module (math is the only one we learnt so far)
How to access variable values defined in a module (see math.pi for example)
Strings: how to create them, how to escape characters, multi-line strings
String ordering (lexicographic ordering)
How to use raw_input(): remember it always returns a string
Boolean data type: distinguish between expressions that return integer/float/string/Boolean
Remember the distinction between = and ==
Boolean value of conditions involving AND/OR/NOT
IF/ELIF/ELSE statements, how to write them. Understand what parts are optional and how they work
Creating, indexing and modifying lists
Remember the same function may work differently and do different things when applied to a different data type
Review all about the different ways to call the print function for multiple line of input
name = 'Eric Cartman'
age = 8
location = 'South Park'
print "Option 1: Student name:", name, 'lives at:', location
print "Student age:", age
print
print "Option 2: Student name:", name, 'lives at:', location, "\nStudent age:", age
print
print "Option 3: Student name: %s lives at: %s Student age: %d" %(name, location, age)
print
Try and see whether you can predict the output.
Now, let’s review all the functions we have learnt in this class.
- Functions that take one or more values as input and return something (input objects/values are not modified)
>>> min(3,2,1) 1 >>> min([3,2,1]) 1 >>> mystr = 'Monty Python' >>> len(mystr) 12
- Functions that take one or more values as input and return nothing (input objects/values are not modified)
>>> def print_max(val1, val2): ... print "Maximum value is", max(val1, val2) ... >>> x1 = 10 >>> x2 = 15 >>> print_max(x1, x2) Maximum value is 15
- Functions that apply to an object, like a string, and return a value (but not modify the object that they apply to)
>>> mystr = 'Monty Python' >>> mystr.replace('o','x') 'Mxnty Pythxn' >>> mystr 'Monty Python' >>> mystr.upper() 'MONTY PYTHON' >>> mystr 'Monty Python'
- Functions that apply to an object, like a list and modify it (but not return anything)
>>> scores = [3,4,5,1] >>> scores.sort() >>> scores [1, 3, 4, 5] >>> scores.append(6) >>> scores [1, 3, 4, 5, 6]
Local vs. global: Can you guess what each of the print statements print and explain why?
def f1(x,y):
return x+y
def f2(x):
return x+y
x = 5
y = 10
print 'A:', f1(x,y)
print 'B:', f1(y,x)
print 'C:', f2(x)
print 'D:', f2(y)
print 'E:', f1(x)