For Loops (Iteration)

Introduction to Software Engineering (CSSE 1001)

Author

Paul Vrbik

Published

March 13, 2025

Introduction

A loop is a control structure that repeats code that belongs to it.

A for-loop is a control structure that, given a group, repeats code for every member of that group in order; generally we use for-loops when we want to loop a finite many times.

for <name> in <iterator>:
    <code>
for x in "abcd":
    print(x)
a
b
c
d

Notice the looping name retains its value.

x 
'd'

Nesting For-Loops

(digits, alphas) = ("012", "xy")
for d in digits:
    for a in alphas:
        print(d + a) 
0x
0y
1x
1y
2x
2y
(digits, alphas) = ("012", "xy")
for d in digits:
    for a in alphas:
        pass  # (Python disallows empty for-loops.)
    print(d + a) 
0y
1y
2y

Note that pass is the empty instruction. It has no effect and simply passes to the next line.

(digits, alphas) = ("012", "xy")
for d in digits:
    for a in alphas:
        pass
print(d + a) 
2y

Note (again) the names used to iterate through the iterator retain their values after the for-loop exists.

Recall an accumulator is a variable which a loop uses to accumulate an aggregate value.

acc = ""
for x in "abcd":
    acc = acc + x
    print(acc)
a
ab
abc
abcd
acc = ""
for x in "abcd":
    acc =  x + acc
    print(acc) 
a
ba
cba
dcba

Exercise 1 Can every for loop be rewritten with only while loops?

Yes!

for x in xs:
    # do something with x

is code equivalent to

k = 0
while k < len(xs):
    # do something with xs[k]
    k += 1

Exercise 2 Can every while loop be rewritten with only for loops?

No! Consider how many times you need to repeat asking a user for correct input.

We could technically accomplish this in Python by enumerating through an iterator that never yields StopIteration and breaks – but this is not in the spirit of our question.

Exercise 3 Write the body of the function.

def remove(c: str, cs: str) -> str:
    """ Return the string with all instances of c removed from cs.
    
    Precondition: 
        len(c) == 1

    >>> remove('b', "bluey" )
    'luey'
    >>> remove('b', "Bluey" )
    'Bluey'
    >>> remove('b', "chilli" )
    'chilli'
    >>> remove('b', "")
    ''
    """
def remove(c: str, cs: str) -> str:
    """ Removes all instances of c from the list cs.
    """
    acc = ""
    for c in cs:
        if not c == x:
            acc += c
    return acc

Or using list comprehension.

def remove(c: str, cs: str) -> str:
    return sum(x for x in cs if x != c)

Exercise 4 Write the body of the function.

def capitalize(cs) -> str:
    """ Return a version of cs with all its alpha characters capitalized.
    >>> capitalize("boom goes the dynamite!")
    'BOOM GOES THE DYNAMITE!'
    >>> capitalize("123")
    '123'
    """
def capitalize(cs: str) -> str:
    """ Capitalize every letter of a string.
    """
    ans = ""
    gap = ord('a') - ord('A')
    for x in cs:
        if 'a' <= x <= 'z':
            ans += chr(ord(x) - gap)  #capitalize
        else:
            ans += x
    return ans

Summary

For loops enable us to iterate through anything iterable. Strictly speaking, they are not necessary (to repeat something k times we could just copy-paste k-times or use a while loop) but are used so often as to merit their introduction.