0% found this document useful (0 votes)
8 views

4 PythonLoops

Uploaded by

Kwok Shi Ming
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

4 PythonLoops

Uploaded by

Kwok Shi Ming
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Another example

To compute the function s(n) = 0+1+2+...+n.


 Note that s(0) = 0, and s(n) = s(n-1) + n.
 Let's try something simpler: write a program to compute s(5).

Our solution cannot be used


to compute s(n) for any n.

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

These five statements are


very similar. By to make
use of the for stmt, they
. have to be “identical”.
..

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

Replace the larger number by the difference of the two numbers


until both are equal.
Example:
(24, 14)  (10, 14)  (10, 4)  (6, 4)  (2, 4)  (2, 2)
Note: 2 is the greatest common divisor of 24 and 14.

Write a Python program that implements Euclid’s algorithm.

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

You might also like