CHAPTER 4
Repetition Structures
What is the output of this flowchart?
Repetition Structures
The program above will calculate the average of three
grades for one student. If we want to calculate the
average for 10 students, it means we need to repeat the
above code 10 times (5 X10=50 lines)
Disadvantages to duplicating code
•Makes program large
•Time consuming
•May need to be corrected in many places
Instead of that, we use repetition structure (loop)
Repetition Structures
•Repetition structure: makes computer repeat included code
multiple times as necessary.
Types of repetition (loops)
condition-controlled loops count-controlled loops
while Loop for Loop
The while Loop: a Condition-Controlled
Loop
while condition:
false
statement(s) condition
true
condition is evaluated
• if it is true, the statement(s) are Statement(s)
executed, and then condition is
evaluated again
• if it is false, the loop is terminated and
the program continues right after the loop
• If the condition is initially false, the
statement(s) in the body of the loop are
never executed
The while Loop: a Condition-Controlled
Loop
•In order for a loop to stop
executing, something has to
happen inside the loop to make
the condition false.
The while Loop: a Condition-Controlled
Loop
•Iteration: one execution of the body of a loop
•while loop is known as a pretest loop
–Tests condition before performing an iteration
•Will never execute if condition is false to start with
•Requires performing some steps prior to the loop.
In the previous example, we assign 1 to i before
the loop.
Infinite Loops
•Loops must contain within themselves a way to terminate
Something inside a while loop must eventually make the
condition false
•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
Common Loop Errors
• Don’t forget indentation:
Using the while Loop for Input Validation
• Loops are an appropriate structure for validating user input
data
1. Prompt for and read in the data.
2. Use a while loop to test if data is valid.
3. Enter the loop only if data is not valid.
4. Inside the loop, display error message and prompt the
user to re-enter the data. The loop will not be exited until
the user enters valid data.
Using the while Loop for Input Validation
Example: Sentinels
• A sentinel is value in a list of values that indicates end of data
• Special value that cannot be confused with a valid value,
e.g., -999 for a test score
• Used to terminate input when user may not know how many
values will be entered
Exercise
Write a program that keeps asking the user to enter a number
and checks if it is odd or even until the user enters 0 prints
“Done…”
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 [val1, val2, etc]:
statements
• Target variable: the variable which is the target of
the assignment at the beginning of each iteration
The Program The output
Using the range Function with the for Loop
range returns an iterable object
•Iterable: contains a sequence of values that can be
iterated over
•range characteristics:
• One argument: used as ending limit
• Two arguments: starting value and ending limit
• Three arguments: third argument is step value
1. Using the range function with one argument
(ending limit)
2. Using the range function two arguments
(starting value and ending limit)
3. Using the range function three arguments
(starting value and ending limit, and steps)
•The range function can be used to generate a
sequence with numbers in descending order
Make sure starting number is larger than end limit, and step
value is negative
Exercise
Use for loop to print the numbers from 1
to 10 and their squares in a table that
has two columns: the number and its
square.
Modify your program to get the
ending limit from the user, for
example if the user enters 5, then
print the numbers and their squares
from 1 to 5.
Accumulator
It is a variable used to keep the running total of numbers that
accumulates with each iteration.
Example 1: write a program to calculate the total of the numbers
5 to 15.
Example 2: write a program to calculate the total of the even
numbers between 5 to 15.
Another way
Example 3: write a program to calculate the average of the
numbers 5,33,2,1,8,55
Example 4: write a program to read 10 integers from user and
print the average.
Turtle Graphics: Using Loops to Draw Designs
• You can use loops with the turtle to draw both
simple shapes and elaborate designs.
for x in range(4):
turtle.forward(100)
turtle.right(90)
for x in range(8):
turtle.forward(100)
turtle.right(45)
Compare while and for
While for
Pretest loop (loop body may Pretest loop (loop body may
not be executed at all) not be executed at all)
Conditional loop Count-Controlled Loop
Useful when the number of Useful with counters or if
repetitions is unknown. precise number of
repetitions is known
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
Nested Loops
•Nested loop: loop that is contained inside another loop
• Inner loop goes through all its repetitions
for each repetition of outer loop
• Inner loop repetitions complete sooner than
outer loop
• Total number of repetitions for the code
inside the inner loop is product of number
of repetitions of the two loops.
Example: write a program to to display the
following pattern
*******
*******
*******
*******
*******
for row in range(6): # for each line
for col in range(8): # print a line
print('*',end='')
print('\n')
Example: write a program to calculate the average score for each one of 10
students, where each students has three tests.
Exercise
Write a program that calculates the total of the factorials
for numbers from 1 to 10.
y=1!+2!+3!+…+10!
Factorial of any number n is calculated as follows:
n!=1X2X3X…X(n-1)Xn
Break statement
The break statement in Python terminates the current
loop and resumes execution at the next statement.
Break statement in Nested loop
What will happen if break is used in a
nested loop?.
In a nested loop, a break statement only
stops the loop it is placed in. Therefore, if a
break is placed in the inner loop, the outer loop
still continues. However, if the break is placed in
the outer loop, all of the looping stops.
Break statement in Nested loop
Break statement in the inner loop
Break statement in Nested loop
Break statement in the outer loop
Continue statement
The continue statement is used to skip the rest of the
code inside a loop for the current iteration only.