Introductory Programming in Python: Lesson 8
Sequential Loops

[Prev: Flow Control: Conditional Loops] [Course Outline] [Next: Lists]

The Necessity of Lists

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 = []
>>>

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"
]

Loops over Lists

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]

else Clauses in for loops

'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]

Exercises

Given the list l = ['There', 'are', 9000000, 'bicycles', 'in', 'Beijing']

  1. How many elements does the list have? How would one find this out programatically?
  2. What is the index of the non-string element?
  3. What is the output of print l[1:4]?
  4. Write a program that asks the user to enter a number from 1 to 12 and prints out the name of the corresponding month.
  5. Write a program that prints out the string "repeat" 100 times.
  6. Write a program that asks the user for their name, and a number, then prints out the user's name a number of times equal to the number they entered.
  7. What is an expression using the range function that yields a list of 10 consecutive integers starting at 0?
  8. What is an expression using the range function that yields a list of 100 consecutive integers starting from 1?
  9. What is an expression using the range function that yields a list of 100 consecutive even integers starting from 2?
  10. Write a program that prints the numbers from 1 to 100 each on its own line.
  11. Write a program that asks the user for a number from 1 to 12, and then prints out the name of corresponding month, and the number of days in that month, in the form: "January has 31 days."
  12. Modify your answer to question 10 from "Flow Control: Conditionals", i.e. print out the numbers from 1 to 10 by which a user entered number is divisible, to use a for loop instead of multiple if statements.
  13. Write a program that asks the user for the height of a triangle. If a blank line is entered, the program finishes, otherwise it prints out a right handed triangle, with the right angle on the bottom right, made of asterisks ('*') of a height equal to the number entered. Example input/output follows ...
    Enter triangle height: 3
    *
    **
    ***
    Enter triangle height: 5
    *
    **
    ***
    ****
    *****
    Enter triangle height: 
    
  14. Same as above, except now with the right angle in the top right! Example ...
    Enter triangle height: 3
    ***
     **
      *
    Enter triangle height: 5
    *****
     ****
      ***
       **
        *
    Enter triangle height: 
    
  15. Write a program that prints out a 'Christmas' tree shape from asterisks. The program should ask the user for the height of the tree, in lines, and the tree should have a stalk of two lines regardless. If the user enters a height, the tree should be printed out, and the user should be prompted for another height until they enter a blank line.
    Enter tree height: 4
       *
      ***
     *****
    *******
       *
       *
    Enter tree height: 6
         *
        ***
       *****
      *******
     *********
    ***********
         *
         *
    
[Prev: Flow Control: Conditional Loops] [Course Outline] [Next: Lists]