for x in "abcd":
print(x)
a
b
c
d
Introduction to Software Engineering (CSSE 1001)
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'
= ("012", "xy")
(digits, alphas) for d in digits:
for a in alphas:
print(d + a)
0x
0y
1x
1y
2x
2y
= ("012", "xy")
(digits, alphas) 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.
= ("012", "xy")
(digits, alphas) 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 + x
acc print(acc)
a
ab
abc
abcd
= ""
acc for x in "abcd":
= x + acc
acc print(acc)
a
ba
cba
dcba
Exercise 1 Can every for
loop be rewritten with only while
loops?
Exercise 2 Can every while
loop be rewritten with only for
loops?
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', "")
''
"""
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'
"""
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.