Chapter6 - Iterative Statements
Chapter6 - Iterative Statements
• What happens if the content of the variable `text` in the loop's code block is changed
?
©CMC Univ. 2022
‘for’ loop
• Example: def print_letters(text):
for letter in text:
print( letter )
if letter == "n":
text = "orange"
print( "Done" )
text = str(input())
print_letters(text)
✓As run this code, changing the contents of the variable `text` has *no effect* on the
result.
✓It means that no `for` loops are endless!
• `for` loop using a range of numbers
✓range(a): generates all integers, starting at zero, up to but not including the parameter.
✓range(a,b): a will be the starting number (default is zero), while b will be the "up to but not
including"
✓range(a, b, c): the third number c will be a step size (default is `1`)
©CMC Univ. 2022
`for` loop
• Example: def print3(a, b, c):
for x in range(a,b,c):
print(x)
a, b, c = input().split(“,”)
print(int(a), int(b), int(c))
print_fruits()
• ‘break’ statement: allows to prematurely break out of a loop.
i = 1
while i <= 10000:
if i%9 == 0 and i%21 == 0:
break
i += 1
print (i, ": is our solution.")
✓Exercise: we can pass the values 9 and 21 to the function as parameters, and make it
more general-purpose.
✓Note: the `break` statement also works for `for` loops. when a `break` statement is
encountered, and the loop also has an `else` clause, the code block for the `else` will
*not* be executed
• Suppose that you want to write a function tat prints all pairs (i,j) where i and j can take on
the values 0 to maximum, but j must be higher than `i
def print_pairs(maximum):
for i in range( maximum ):
for j in range( i+1, maximum ):
print( " ", i, ",", j)
©CMC Univ. 2022
print_pairs(6)
nested loops
• You can also triple-nest loops, quadruple-nest loops, or go even deeper
def nested_loop3(n):
for i in range( 3 ):
for j in range( 3 ):
for k in range( 3 ):
print( i, ",", j, ",", k)
n = int(input())
nested_loop3(n)
• `while` loops
• `for` loops
• Endless loops
• Nested loops