Repetition Structures
• Introduction to Repetition Structures
• The while Loop: a Condition-Controlled Loop
• The for Loop: a Count-Controlled Loop
• Augmented assignment operators
• Nested Loops
• Use loops to solve problems
4-1
Introduction to Repetition Structures
• In many cases, we need to write code that performs
the same task multiple times
– Disadvantages to duplicating code
Makes program large
Time consuming
May need to be corrected in many places
• Repetition structure: makes computer repeat same
task as necessary
– Includes condition-controlled loops and count-
controlled loops
4-2
The while Loop: a Condition-
Controlled Loop
• while loop:
while condition is true, do something
General format:
while condition:
statements
– Two parts:
condition tested for true or false value
statements repeated as long as condition is true
– In flow chart, line goes back to previous part
4-3
The while Loop: a Condition-
Controlled Loop
Figure 4-1 The logic of a while loop
4-4
The while Loop: a Condition-
Controlled Loop
Example:
num = 0
while num < 2:
print( ‘hello world’ )
num = num + 1 #changing the condition
• In order for a loop to stop executing, something has to
happen inside the loop to make the condition false,
otherwise the program keeps executing the same
code block infinitely, we call it infinite loop.
4-5
The while Loop: a Condition-
Controlled Loop
• Infinite loop: loop that does not have a way of
stopping
– Repeats until program is interrupted
– Occurs when programmer forgets to include stopping
code in the loop
• Iteration: one execution of the body of a loop
4-6
The for Loop: a Count-Controlled Loop
• Count-Controlled loop: iterates a specific number of
times
– Use a for statement to write count-controlled loop
Designed to work with sequence of data items
– Iterates once for each item in the sequence
General format:
for variable in [a collection of data]:
statements
Example:
for num in [1,2,3,4,5]:
print(num)
4-7
For Loop
• The variable num is called target variable, which
references each item in a sequence as the loop
iterates.
• First iteration: num references the value 1
• Second iteration: num references the value 2
• Third iteration: num references the value 3
• ……
4-8
The for Loop: a Count-Controlled Loop
Figure 4-4 The for loop
4-9
Using the Variable Inside the Loop
for num in [1,2,3,4,5]:
print(num)
• The program above just prints the value of target
variable num
• Target variable can be used in calculations or tasks in
the body of the loop
– Example: calculate and display square of each number
for num in [1,2,3,4,5]:
print(num*num)
4 - 10
Using the range Function with the for
Loop
• The built-in range function simplifies the process of
writing a for loop
– range returns an iterable object
Iterable: contains a sequence of values that can be
iterated over
• Range can be used in three different ways:
– Takes one number as ending limit
– Takes two numbers as starting value and ending limit
– Takes three numbers as starting value, ending limit and
step value
4 - 11
Using the range Function with the for
Loop
• range Takes one number as ending limit:
range(5) generates the following sequence:
0,1,2,3,4
range(10) generates the following sequence:
0,1,2,3,4,5,6,7,8,9
In general, range(n) generates a sequence starting
from 0 up to n-1 ( n here is a number )
4 - 12
Using the range Function with the for
Loop
• range Takes two numbers as starting value and
ending limit:
range(1,5) generates the following sequence:
1,2,3,4
range(5,10) generates the following
sequence:
5,6,7,8,9
In general, range(n,m) generates a sequence starting
from n up to m-1 ( n, m here are numbers )
4 - 13
Using the range Function with the for
Loop
• range Takes three numbers
• First number is the starting value
• Second number is the limit value
• Third number is the step of the sequence
range(1,10,2) generates the following
sequence:
1,3,5,7,9
range(5,20,5) generates the following
sequence:
5,10,15
4 - 14
Using the range Function with the for
Loop
Examples of range function used in the
for loop:
for num in range(5):
print(num)
for num in range(1,10):
print(num**2)
for num in range(5,20,2):
print(2*num)
4 - 15
Use For Loop to solve problems
• For loop can be used to calculate a total of a series of
numbers
– Typically include two elements:
A loop that reads each number in series
An accumulator variable
– Known as program that keeps a running total:
accumulates total and reads in series
– At end of loop, accumulator will reference the total
4 - 16
Use For Loop to solve problems
Figure 4-6 Logic for calculating a running total
4 - 17
Use For Loop to solve problems
Example:
total = 0 # accumulator variable
for num in [1,2,3]:
total = total + num
First iteration: num is 1, total gets 1
Second iteration: num is 2, total now gets 3
Third iteration: num is 3, total gets 6
After the loop, the value of total is 6, which is the sum of
all numbers in the sequence
4 - 18
The Augmented Assignment Operators
• In many assignment statements, the variable on the
left side of the = operator also appears on the right
side of the = operator
• Augmented assignment operators: special set of
operators designed for this type of job
– Shorthand operators
• The statement in the example total = total +
num can be written as: total += num
4 - 19
The Augmented Assignment Operators
Table 4-2 Augmented assignment operators
Operator Example Usage Equivalent To
+= x += 5 x = x + 5
−= y −= 2 y = y − 2
*= z *= 10 z = z * 10
/= a /= b a = a / b
%= c %= 3 c = c % 3
//= x //= 3 x = x // 3
**= y **= 2 y = y**2
4 - 20
break and continue statements
• break and continue are flow control statements
used within the loop to alter their execution.
break // break statement
continue // continue statement
• break
Terminates the loop prematurely, and the control
flow jumps to the statement immediately
following the loop.
• continue:
skips the rest of the code inside of the loop for
the current iteration and proceeds to the next
iteration. 4 - 21
Break statement
• Break: Terminate the loop
for i in range(5):
if i == 3: Jump out of the loop
break
print(i)
print(“out of the loop”)
print(“the current value of i == “, i
)
When i == 3, it executes break statement
which terminates the loop, as a result, it
4 - 22
Break statement
When i == 3, it executes break statement which
terminates the loop, as a result, it displays three
numbers 0, 1, 2.
The last statement will display:
the current value of i == 3
Because the for loop terminates when i == 3
4 - 23
continue statement
• continue: skips the rest of statement of
current iteration only
n=0
next iteration
while n < 10:
n += 1
if n % 2 == 0:
continue
print(n)
The program above displays odd numbers
only.
4 - 24
continue statement
• continue: skips the rest of statement of
current iteration only
n=0
while n < 10:
if n % 2 == 0:
continue
print(n)
n += 1
Any problem in this program?
4 - 25
Nested Loops
• Nested loop: loop that is contained inside another loop
– Example:
count = 0
while count < 3 :
for num in range(10):
print( num )
count += 1
Or:
for i in range (1, 4 ):
for num in range(10):
print(num**i)
4 - 26
Nested Loops
• Nested loop: loop that is contained inside another loop
– Another Example:
for i in range (1, 4 ): # sequence 1,2,3
for num in range(10):
print( num**i )
The program calculates and display the result of to the
power of 1, square and cube of each number from 0 to 9.
4 - 27
Break used in nested loops
• Break statement in nested loop is to terminate the
nearest enclosing loop.
for i in range (3): #sequence 0, 1, 2
print(‘the outer loop’, i )
for j in range(3):
print(‘inner loop’, j )
if j == 1:
break
The break statement terminates the inner loop
What is the output of the program?
4 - 28
Break used in nested loops
• Break statement in nested loop is to terminate the
nearest enclosing loop.
for i in range (3): #sequence 0, 1, 2
print(‘the outer loop’, i )
for j in range(3):
print(‘inner loop’, j )
if i == 1:
break
The break statement terminates the outer loop
What is the output of the program?
4 - 29
continue in nested loops
• Similarly continue statement in nested loop is to
terminate the current iteration of the nearest enclosing
loop.
for i in range (3): #sequence 0, 1, 2
print(‘the outer loop’, i )
for j in range(3):
if j == 1:
continue
print(‘inner loop’, j )
The continue statement terminates the current iteration of
the inner loop 4 - 30
continue in nested loops
• Similarly continue statement in nested loop is to
terminate the current iteration of the nearest enclosing
loop.
for i in range (3): #sequence 0, 1, 2
print(‘the outer loop’, i )
for j in range(3):
print(‘inner loop’, j )
if i == 1:
continue
The continue statement terminates the current iteration of
the inner loop
What is the output? 4 - 31
Nested Loops
• Key points about nested loops:
– Inner loop goes through all of its iterations for each
iteration of outer loop
– Inner loops completes their iterations faster than outer
loops
– Break and continue in nested loop terminates the
execution of the nearest enclosing loop.
– Total number of iterations in nested loop:
number of iterations of inner loop X number of iterations of outer loop
4 - 32
Practice questions
1. Write a for loop to print hello world five times.
2. Write a while loop to print hello world five times.
3. Write a program to calculate the sum of integers from 1
to 10, ie
sum = 1 + 2 + 3 + … + 10
4. Write a program to calculate the sum of all odd numbers
from 1 to 99.
4 - 33
Practice questions
4. Use for loop to find out the largest number among the
numbers :
[ 23, 45, 1, 3, 67, 112, 7 ]
5. Write a program that keeps asking the user to input
numbers, display the number if it’s an even number, the
program should stop ( quit ) only when the user input a
string ‘exit’. ( two versions: with break or without break )
4 - 34
Summary
• This chapter covered:
– Repetition structures, including:
Condition-controlled loops
Count-controlled loops
Nested loops
– Infinite loops and how they can be avoided
– range function as used in for loops
– Break and continue statements
– Nested loops
– Augmented assignment operators
– Use loops to solve problems
4 - 35