Let us for the sake of originality work on a new problem.
A lecturer for an introductory programming course wants to record some information about his students. He wants to keep a record of each student's name, their primary field of study, and a brief description of their current research project. He would like to be able to print this out in a nicely formatted way. His class has 19 students.
For each student we need to record their name, field of study, and a description of their research project. This means three values we need to store for each student, or 38 variables in total. Surely there's a better way. There is, and python yet again provides us with the perfect tool for job, the list!
A list is a type of variable. To create a new variable of type list in python simply assign a variable to a list. Lists are formed using square brackets surrounding a comma separated sequence of the elements of the list. Example:
Python 2.4.3 (#1, Oct 2 2006, 21:50:13) [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> mylist = [1, 2, 3] >>> anotherlist = ["Alice", "Bob", "Carl", "Mallory"] >>> mixed = ["a string", 143, [341]] >>> empty = [] >>>
list[index]
. This expression evaluates to the element
in the index'th position of the list. e.g. mylist[0]
is 1, mylist[1]
is 2, mixed[2]
is
[341].Now that we know about lists, we could use a list to represent the students names, another to represent their fields of study, and a third to represent their project descriptions. So we might have
#a small program to record info about students name = ["Alice", "Bob", "Carl", "Mallory"] field = ["Astronomy", "Biochemistry", "Cancer Research", "Maths"] description = [ "The search for black holes", "Engineering a better yeast for brewing beer", "Better pain management in palliative care", "Finding a polynomial time solution for NP-complete problems" ]
There would of course be nineteen elements to each list in our real solution, but the code above illustrates how to create a list well enough. But now we have this information stored in our lists how do we access every element in it, for example to print it out in a nicely formatted way. Well we could use a while loop, since we know the length of the list, as in
index = 0 while index < 4: print "Student:", name[index] print "\tField:", field[index] print "\tProject:", description[index] index += 1
But, once again provides us a better tool for the job in the form of the for statement.
The for statement is also a looping statement, except that it loops over the elements of a list. It looks like this
for <element> in <list>: statement statement ...
Where 'element' is a variable name (not necessarily 'element'), which may be as yet unassigned (the for statement will assign a value to it), or may be an already extant variable, in which case a new value will be assigned to that variable by the for statement. 'list' is an expression whose value is of type list.
What this does exactly is execute the indented statements once for each element in the list 'list'. Each time the statements are executed, the variable in the position of 'element' is assigned the value of the next element in 'list', starting with the first.
So, for example, the following program
#a small program to record info about students name = ["Alice", "Bob", "Carl", "Mallory"] field = ["Astronomy", "Biochemistry", "Cancer Research", "Maths"] description = [ "The search for black holes", "Engineering a better yeast for brewing beer", "Better pain management in palliative care", "Finding a polynomial time solution for NP-complete problems" ] for index in [0, 1, 2, 3]: print "Student:", name[index] print "\tField:", field[index] print "\tProject:", description[index]
produces the following output
Student: Alice Field: Astronomy Project: The search for black holes Student: Bob Field: Biochemistry Project: Engineering a better yeast for brewing beer Student: Carl Field: Cancer Research Project: Better pain management in palliative care Student: Mallory Field: Maths Project: Finding a polynomial time solution for NP-complete problems
Well, that's pretty cool. But if we were dealing with larger lists, like of 19 students, or even thousands of students, we really don't want to have to type out the list of possible indexes ([0, 1, 2, ..., 19]) every time. Python again comes to the rescue with another built in function, range. 'range' returns a list of numbers within a given range, and defined as follows
range([start,] stop [, step])
What it does is returns a list of integers, starting with the number given by 'start' (or 0 if start is not given), up to but not including the number given by 'stop'. If 'step' is given, the list will only provide every step'th integer in the sequence. Examples probably illustrate this better ...
>>> range(5) [0, 1, 2, 3, 4] >>> range(4,10) [4, 5, 6, 7, 8, 9] >>> range(-3,3) [-3, -2, -1, 0, 1, 2] >>> range(0,10,2) [0, 2, 4, 6, 8] >>> range(10,20,3) [10, 13, 16, 19] >>>
So we can change our previous program slightly, as follows
#a small program to record info about students name = ["Alice", "Bob", "Carl", "Mallory"] field = ["Astronomy", "Biochemistry", "Cancer Research", "Maths"] description = [ "The search for black holes", "Engineering a better yeast for brewing beer", "Better pain management in palliative care", "Finding a polynomial time solution for NP-complete problems" ] for index in range(len(name)): print "Student:", name[index] print "\tField:", field[index] print "\tProject:", description[index]
'for loop' statements may also have an else clause, which is executed when the list is exhausted, but not when the loop is terminated by a break statement.
for <variable> in <list>: <statement> [statement] else: <statement> [statement]
Given the list l = ['There', 'are', 9000000, 'bicycles', 'in', 'Beijing']
print l[1:4]
?Enter triangle height: 3 * ** *** Enter triangle height: 5 * ** *** **** ***** Enter triangle height:
Enter triangle height: 3 *** ** * Enter triangle height: 5 ***** **** *** ** * Enter triangle height:
Enter tree height: 4 * *** ***** ******* * * Enter tree height: 6 * *** ***** ******* ********* *********** * *