4 PythonLoops
4 PythonLoops
1
Trick: Reuse the variables
After s1 is computed, we no longer need s0.
We can reuse s0 to store the value of s1,
s0 = s0 + 1
Similar, for s2, which now should be
s2 = s0 + 2
can be rewritten as
s0 = s0 + 2,
...
2
Transform to loop-stmt with only one
"index-variable" changes
3
Reuse the variables
i ranges through 1,2,...,5,
and for each value of i,
execute the loop body
s=s+i
4
Solution using the for stmt.
Recall that range(1,6) is [1,2,3,4,5],
5
Solution using the for stmt.
Generalize to any n
6
Example: An exam question
Write a Python program that input an integer string, and print the string of letters representing
this integer string.
7
In-class exercise: The Euclid’s algorithm for finding the
greatest common divisor
8
Exercise: Rewrite the magic square program using loops
9
Nested loops
For many problems, it is natural to have a loop within the body of
some loop.
Read an integer k, and then print a right triangle of k rows of ‘*’, in
which the first row has one ‘*’, the 2nd row has two ‘*’, ..., the kth
row has k ‘*’.
If k = 5, the program should print
*
**
***
****
*****
Suggested solution:
k = int(input())
for i in [1,2,3,..., k]:
print a line of i “*”
10
The break statement
The break statement terminates the loop containing it.
Control of the program flows to the statement immediately
after the body of the loop.
If the break statement is inside a nested loop,
the break statement will terminate the innermost loop.
11
The continue statement
The continue statement is used to skip the rest of
the code inside a loop for the current iteration
only.
Loop does not terminate but continues on with the
next iteration.
12
In-class exercises solutions
13
Euclid’s algorithm
14
Encrypt an integer string
15
Triangle
16
magic square with loop
17