8 Going Loopy

Often when coding there’s a requirement to repeat the same statements over and over again, and one way of doing this is using commands called loops. In this chapter for loops and while loops are covered.

Take this example, if you have your movie collection stored in a list you could display it on screen with the following program:

lisMovies = ["exorcist, the" , "fearless", "hot shots", "kingpin",  "life of brian", "scream", "star wars"]

print (lisMovies[0])
print (lisMovies[1])
print (lisMovies[2])
print (lisMovies[3])
print (lisMovies[4])
print (lisMovies[5])
print (lisMovies[6])

Here you use 7 statements to print the contents of the List, one for each element. If your movie collection was 1000 titles strong then this method would require the same number of print statements, and would be quite cumbersome to type. There is an easier and shorter way, making the computer do the work for you – using a for loop:

lisMovies = ["exorcist, the" , "fearless", "hot shots", "kingpin",  "life of brian", "scream", "star wars"]

for strMovie in lisMovies:
print (strMovie)

Here the for statement goes through each element of the list, and executes the block of code which follows, in this case the single print statement. Each element in the list as assigned to the strMovie variable and this is displayed on the screen with the print command. The for loop will go through every element in the list until it reaches the end, in this case 7 times, and each time it executes the block of code (each pass through the code block is called an iteration.) It doesn’t matter how long your movie list is, the above for loop will print each and every one.

WHILE LOOPS

for loops are useful for processing the elements of a list, but there is another more general looping command in Python (and one that is common in other programming languages too) – the while loop.

A while loop will keep repeating a block of code for as long as a condition is true. Consider this:

intCount = 1
while intCount < 11:
print ("feck the world")
intCount = intCount + 1

Here intCount is first given the value of 1 and then the while loop begins. It tests to see if intCount is below 11 which it is, so the statements in the indented block are processed. The print statement displays a message on the screen and then intCount is increased by 1. After doing this, the computer goes back to the beginning of the while statement and tests again to see if the variable is below 11. It has the value of 2 now, so the comparison is true, and the block is executed again. It keeps repeating this process until intCount becomes 11 and is no longer less than 11, so the test is false and the while loop finishes.

When writing while loops it’s important to change the value of the variable used in the comparison, so that eventually the test fails and the loop comes to an end. If this isn’t done, the while loop will repeat forever (known as an infinite loop) which is usually an undesirable situation. (If this happens you can terminate a running program by pressing Control + Z or Control + C)

Another example of a while loop, here the code repeats until the correct password is input by the user:

strPassword = "friend"
strInput = input("What is the password? ")
while strInput != strPassword:
print ("Incorrect password try again..")
strInput = input("What is the password? ")
print ("Password accepted, you may enter")

CONTINUE

If you want to move back to the beginning of a loop and avoid processing the rest of the commands in the block, it’s possible to do this with the continue keyword as part of an if statement. For instance:

intCount = 0
while intCount < 10:
intCount = intCount + 1
if intCount == 5:
continue
print ("%d feck the world" % intCount)

In this loop we test if intCount equals 5 and if it does issue the continue keyword. This results in going back to the beginning of the while statement, and avoids processing the print command, so that the fifth line is never displayed on screen.

BREAK

Sometimes you want to stop the loop completely based on a certain condition, this is called breaking out of the loop and uses naturally enough the break keyword:

intCount = 0
while intCount < 10:
intCount = intCount + 1
if intCount == 5:
break
print ("%d feck the world" % intCount)

Here the loop stops abruptly once intCount equals 5 and only 4 lines are displayed on screen instead of 10.

NESTED LOOPS

It’s possible to have loops inside other loops, an inner one and an outer one, this is called nesting. The following will display the 10 times multiplication table:

intOuter = 1
while intOuter <= 10:
intInner = 1
while intInner <= 10:
intResult = intInner * intOuter
print(intResult, "\t", end="")
intInner += 1
intOuter += 1
print("")

The inner loops goes through the numbers 1 to 10 and displays each row of the table. The outer loop runs the inner loop 10 times, displaying 10 rows. In the first print statement the “\t” means insert a tab so that the table is more neatly presented. The end=”” part stops the print command from starting a new line, it continues printing on the same line, which is required for the numbers in each row. Once a row is completed a newline is needed, this is provided by the second print(“”) command.

<– back to contents