0% found this document useful (0 votes)
13 views28 pages

Python Loops: While and For Statements

Python

Uploaded by

phfung1109
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views28 pages

Python Loops: While and For Statements

Python

Uploaded by

phfung1109
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 4.

Python Loops

2022-2023
COMP1117A Computer Programming
Dr. T.W. Chim (twchim@[Link]) & Dr. H.F. Ting (hfting@[Link])
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 (twchim@[Link]) & Dr. H.F. Ting (hfting@[Link])
Department of Computer Science, The University of Hong Kong

Common questions

Powered by AI

Nested loops in Python are beneficial for handling multi-dimensional data structures, such as matrices or tables, where operations need to be performed iteratively on each dimension. They're useful for tasks like creating patterns, searching within linked data, and performing matrix operations. The primary benefit lies in their ability to traverse comprehensive data sets hierarchically, simplifying otherwise complex algorithmic implementations .

Implementing Euclid’s algorithm in Python illustrates the decision between using a 'for' or 'while' loop. Since the number of iterations is determined by the dynamic difference between two numbers getting reduced to zero, a 'while' loop is typically preferred. The loop can repeatedly apply the algorithm's rules, updating inputs until the condition is met. This flexibility ensures the loop accommodates varying input sizes and changing conditions .

The 'break' and 'continue' statements significantly alter control flow within loops. 'Break' immediately exits the innermost loop containing it, transferring control to the following statement after the loop. This can end multiple iterations prematurely. 'Continue', on the other hand, skips the remaining statements in the current loop iteration, moving control back to the loop's condition check or the next iteration step. In nested loops, 'break' only affects the current loop, whereas 'continue' applies to its containing loop .

Transforming repeated statements into a loop involves identifying common structural patterns and redundancy. First, isolate the variable or sequence of operations that changes with each repetition. Next, define a loop that encapsulates the repetition logic using a control structure like 'for' or 'while'. Within the loop, manage the changing parameters via index variables or conditions, ensuring the loop maintains the original intended functionality through indexed iterations .

Indentation in Python loops is critical as it defines the scope of the loop body. All the statements that are intended to be executed in each iteration of the loop must be indented at the same level. This indentation ensures that the program's structure is clear and correctly reflects the intended logic .

Choosing between a 'for' loop and a 'while' loop depends on the nature of the iteration count. A 'for' loop is suitable for scenarios with a known, fixed number of iterations as it offers concise syntax and a clear loop structure. Conversely, a 'while' loop is preferable when the number of iterations is not predetermined, as it controls execution based on a condition's truth value, which ideally changes within the loop to eventually terminate it .

A practical method for computing the sum of integers up to a given number 'n' in Python is using a 'for' loop to iterate over a range, adding each integer to an accumulating variable. For example, using 'for i in range(1, n+1)', you can incrementally add 'i' to a sum variable initialized as zero. This implements the formula 's(n) = s(n-1) + n' iteratively, facilitating summation up to 'n' .

The 'while' statement in Python repeatedly executes a target statement as long as a given condition is true. The process for determining whether the loop should continue involves evaluating the condition to see if it's true or false. If true, the loop-body executes once, and the condition is re-evaluated. If false, the loop stops, and control passes to the code immediately following the loop .

In a 'for' loop, the 'range' function generates a sequence of numbers, which allows the loop to iterate over these elements. With 'range(a, b)', it generates numbers from 'a' to 'b-1'. The function can also accept a step with 'range(a, b, t)', generating numbers from 'a' to a maximum of 'b' - 1, increasing by 't' each time. The default step is 1 if not specified. Understanding this helps in customizing the bounds and increments of loops .

Reusing variables in iterative structures optimizes code by minimizing the memory footprint and potentially reducing computation time. For instance, when computing a sequence of sums, previously used variables can store subsequent results, updating in place. This technique avoids the unnecessary creation of new variables for each iteration step, thereby optimizing the code for better performance .

You might also like