04_Python_Lecture_updated (1)
04_Python_Lecture_updated (1)
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
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
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
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
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
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
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
4 - 16
Use For Loop to solve problems
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
4 - 19
The Augmented Assignment Operators
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)
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)
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:
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
4 - 32
Practice questions
1. Write a for loop to print hello world five times.
4 - 33
Practice questions
4. Use for loop to find out the largest number among the
numbers :
[ 23, 45, 1, 3, 67, 112, 7 ]
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