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

Chapter 4 PythonLoops

Python

Uploaded by

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

Chapter 4 PythonLoops

Python

Uploaded by

phfung1109
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Chapter 4.

Python Loops

2022-2023
COMP1117A Computer Programming
Dr. T.W. Chim ([email protected]) & Dr. H.F. Ting ([email protected])
Department of Computer Science, The University of Hong Kong
Loop
Used when we want to repeat a set of instructions
many times.

Yes
exam<50

No Yes
Re-exam
exam<50
Pass this Fail this (new exam mark)
course course
No

IF-ELSE loop 2
The while statement
 In general
while (condition): condition

loop-body
true false

loop-body
 To execute the statement
1. determine if the condition is true/false.
2. If true, execute the loop-body once, and
then go back to Step 1. flow chart for
while
3. If false, stop the while statement, and
executing the following statement.

3
The while statement
 A statement for implementing loops.
i < 10?

yes no
loop
body print “Hello”
i=i +1

4
The for statement
 An equivalent program using the for statement
First, 0 assigned to i and execute loop body
Then, 1 assigned to i and execute loop body
Then, 2 assigned to i and execute loop body
...
Finally, 9 assigned to i and exectue loop
body

loop-body, the statement (or sequence of statements)


to be executed in each iteration (pass).
Note that the indentation is very important.
5
A simple way to generate
[0,1,2,3,4,5,6,7,8,9]: range(10)

Will also print 10 “Hello”

6
What does “for i in …” really do?

loop body

i is assigned each of the


elements in the list one by one,
and for each assignment,
execute the loop body once.
7
More on range()
range(a, b) gives
a, a+1, a+2, ..., a+k
where
k is the largest integer
with a+k < b

range(a, b, t) gives
a, a+t, a+2t, ..., a+kt
where
k is the largest integer
with a+kt < b
8
"for i in …": … can be any group of values, even
set is allowed

For dictionary, only the


keys will be assigned to i

9
Using for to create a table
Examples:
 Creating a list of n zeros
[0 for j in range(10)] / list(0 for j in range(10))
 Creating a table of 3 rows, 10 columns with zeros.
[[0 for j in range(10)] for k in range(3)]
 Create a list [1, 2, 3, …, 100]
[k for k in range(1, 101)] / list(k for k in range(1, 101))

10
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 simple: write a program to compute s(5).

Our solution cannot be used


to compute s(n) for any n.

11
Reusing Variables
After s1 is computed, we no longer need s0.
We can reuse s0 to store the value of s1,
s0 = s0 + 1
Similarly, for s2, which now should be
s2 = s0 + 2
can be rewritten as
s0 = s0 + 2,
...

12
Reusing Variables

These five statements


are very similar. But to
make use of the for
. statement, they have to
..
be “identical”.

13
Transform to loop-statement with only one
"index-variable" changes
i ranges through 1,2,...,5, and for each value of i,
execute the loop body s = s + i

14
Solution using for statement
Recall that range(1,6) is [1,2,3,4,5],

15
Solution using for statement
Generalize to any n

16
Example: An Exam Question

Write a Python program that input an integer string, and print the string of
letters representing this integer string.

17
Sample Solution

end=“” in print() can ensure that the


output will not go to a new line.

18
In-class exercise 1: 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.

Challenge: Should we use for loop or while loop? Do we know


the number of iterations in advance?
19
In-class exercise 2: Rewrite the magic square program
using loops

20
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 ‘x’, in
which the first row has one ‘x’, the 2nd row has two ‘x’, ..., the kth row
has k ‘x’.
 If k = 5, the program should print
x
xx
xxx
xxxx
xxxxx

 Suggested solution:
k = int(input())
for i in [1,2,3,..., k]:
print a line of i ‘x’
21
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.

22
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.

23
Solutions to
In-class Exercises

24
Euclid’s algorithm

25
Magic Square with Loop

26
We are with you!

“If you face any problems in understanding the materials in


the lectures or the tutorials, please feel free to contact me or
our TAs.
We are always with you!
We wish you enjoy learning programming in this class ☺.”
Chapter 4.

END

2022-2023
COMP1117A Computer Programming
Dr. T.W. Chim ([email protected]) & Dr. H.F. Ting ([email protected])
Department of Computer Science, The University of Hong Kong

You might also like