Loops

The for loop

In Python the ‘for’ loop has the following structure:

for (item) in (iterable):
    (body)

The item is a variable name that can be used in the body and iterable can be a string, list, tuple, sets, or dicts. Here are some examples:

for item in ['one', 'three', 'five']:
    print(i)

one
three
five
for letter in 'Python':
    print(letter)

P
y
t
o
n
my_dict = {'Alex': 60, 'Anthony': 24, 'Erika': 21}
for key in my_dict.keys():
    print(key + ' is', my_dict[key], 'years old.')

Alex is 60 years old.
Anthony is 24 years old.
Erika is 21 years old.

In programs it is common to iterate through a sequence of integers. Recall the range function, ‘range(start, stop, step)’, is a iterator that generates integers. It can be used in a loop like this:

for i in range(5):
    print(i)

0
1
2
3
4

vowels = 'aeiou'
alphabet = 'abcdefghijklmnopqrstuvwxyz'
consonants = ''
for let in alphabet:
     if let not in vowels:
     consonants += let
print('The consonants are:', consonants)

The consonants are: bcdfghjklmnpqrstvwxyz

The while loop

The while loop is used when we want to repeat code until a condition is met. This the structure of the while loop in Python:

while (condition):
    (body)

Here is an example:

lst = ['one', 'two', 'three', 'stop', 'four', 'five']
i = 0
item = lst[0]
while item != 'stop':
    print(item)
    i += 1
    item = lst[i]
one
two
three

Using `break`, `continue`, and `else` with a `while`

A `while` loop with a ‘break’

The break statement will terminate a while loop. Here is a common idea. We want to leave it up to the user to continue “playing” until he wants to stop. Here is some code that uses the while/break to do this.

while True:
    response = input('I will keep going until you input Y or y.\n')
    if response in 'yY':
        break
    print('You input', response, 'so I will keep going.')
print('You input', response, 'so I stopped.')

I will keep going until you input Y or y.
a
You input a so I will keep going.
I will keep going until you input Y or y.
b
You input b so I will keep going.
I will keep going until you input Y or y.
c
You input c so I will keep going.
I will keep going until you input Y or y.
Y
You input Y so I stopped.

A while loop with continue

The continue statement will move control of the execution back to the top of the loop.

A while loop with else looks like this:

while (condition):
    (body)
else:
    (more body)

The else statement executes when the condition is false. One way to use this is to decide whether the while loop was terminated by a break or because the condition failed.

count = 0
breaker = 11
while(count < 10):
    count += 1
    if breaker == count:
        break
else:
    print('The else has been executed.')
print('The while loop looped', count,'times.')
> The else has been executed.
> The while loop looped 10 times.

Since the condition count < 10 fails the else statement is executes after 10 iterations of the loop.

count = 0
breaker = 10
while(count < 10):
    count += 1
    if breaker == count:
        break
else:
    print('The else has been executed.')
print('The while loop looped', count,'times.')

> The while loop looped 10 times.

With breaker set to 10 the loop still iterates 10 times. But the else statement is not executed. On the last iteration the if condition is met before the while condition is checked.

Nested Loops

articles = ['A','The']
verbs = ['walks', 'talks', 'jumps']

for article in articles:
    for verb in verbs:
        print(article + ' child ' + verb + '.')

A child walks.
A child talks.
A child jumps.
The child walks.
The child talks.
The child jumps.

Here is another example. On an 8 x 8 chessboard the rows are labeled from 1 to 8 and the columns are labeled for a to h. Let’s generate a list of strings that represent each square on a chess board for example ‘e4’.

Put an image here

Chessboard

squares = []
for i in range(8, 0, -1):
    for let in 'abcdefgh':
        print(let + str(i), end = ' ')
    print()

a8 b8 c8 d8 e8 f8 g8 h8
a7 b7 c7 d7 e7 f7 g7 h7
a6 b6 c6 d6 e6 f6 g6 h6
a5 b5 c5 d5 e5 f5 g5 h5
a4 b4 c4 d4 e4 f4 g4 h4
a3 b3 c3 d3 e3 f3 g3 h3
a2 b2 c2 d2 e2 f2 g2 h2
a1 b1 c1 d1 e1 f1 g1 h1

The extra parameter end specifies how to end the print statement. The default is a newline. The print() prints a newline. It is indented just one level so that it will execute each time the inner for loop finishes iterating. This way the rows of the output consist of all the squares for each letter. We reverse the range() so that the output will look like a chessboard from White’s perspective.