Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Gauld A.Learning to program (Python)_1.pdf
Скачиваний:
23
Добавлен:
23.08.2013
Размер:
1.34 Mб
Скачать

Looping - Or the art of repeating oneself!

What will we cover?

How to use loops to cut down on repetitive typing. Different types of loop and when to use them.

In the last exercise we printed out part of the 12 times table. But it took a lot of typing and if we needed to extend it, it would be very time consuming. Fortunately there is a better way and its where we start to see the real power that programming languages offer us.

FOR Loops

What we are going to do is get the programming language to do the repetition, substituting a variable which increases in value each time it repeats. In Python it looks like this:

>>>for i in range(1,13):

... print "%d x 12 = %d" % (i, i*12)

...

Note 1: We need the range(1,13) to specify 13 because range() generates from the first number up to, but not including, the second number. This may seem somewhat bizarre at first but there are reasons and you get used to it.

Note 2: The for operator in Python is actually a foreach operator in that it applies the subsequent code sequence to each member of a collection. In this case the collection is the list of numbers generated by range(). You can prove that by typing print range(1,13) at the python prompt and seeing what gets printed.

Note 3: The print line is indented further than the for line above it. That is a very important point since it's how Python knows that the print is the bit to repeat. It doesn't matter how much indentation you use so long as it's consistent.

Note 4: In the interactive interpreter you need to hit return twice to get the program to run. The reason is that the Python interpreter can't tell whether the first one is another line about to be added to the loop code or not. When you hit Enter a second time Python assumes your finished entering code and runs the program.

So how does the program work? Let's step through it.

First of all, python uses the range function to create a list of numbers from 1 to 12.

Next python makes i equal to the first value in the list, in this case 1. It then executes the bit of code that is indented, using the value i = 1:

print "%d x 12 = %d" % (1, 1*12)

Python then goes back to the for line and sets i to the next value in the list, this time 2. It again executes the indented code, this time with i = 2:

print "%d x 12 = %d" % (2, 2*12)

It keeps repeating this sequence until it has set i to all the values in the list. At that point it moves to the next command that is not indented - in this case there aren't any more commands so the program stops.

38