Chapters 5
Loops
Introduction
A loop can be used to tell a program to execute statements
repeatedly.
Suppose that you need to display a string (e.g., programming is
fun!) 100 times.
count = 0
while count < 100:
print("Programming is fun!")
count = count + 1
Python provides two types of loop statements: while loops and
for loops.
The while loop is a condition-controlled loop; it is controlled by
a true/false condition.
The for loop is a count-controlled loop that repeats a specified
number of times.
The while Loop
https://docs.python.org/3/reference/compound_stmts.html#the-while-statement
A while loop executes statements repeatedly as long as a
condition remains true.
The syntax for the while loop is:
while loop-continuation-condition:
# Loop body
Statement(s)
RepeatSubtractionQuiz.py
import random
# 1. Generate two random single-digit integers
number1 = random.randint(0, 9)
number2 = random.randint(0, 9)
# 2. If number1 < number2, swap number1 with number2
if number1 < number2:
number1, number2 = number2, number1
# 3. Prompt the student to answer "What is number1 - number2?"
answer = eval(input("What is " + str(number1) + " - " +
str(number2) + "? "))
# 4. Repeatedly ask the question until the answer is correct
while number1 - number2 != answer:
answer = eval(input("Wrong answer. Try again. What is " +
str(number1) + " - " + str(number2) + "? "))
print("You got it!")
Loop Design Strategies
Step 1: Identify the statements that need to be repeated.
Step 2: Wrap these statements in a loop like this:
while True:
Statements
Step 3: Code the loop-continuation-condition and add
appropriate statements for controlling the loop.
while loop-continuation-condition:
Statements
Additional statements for controlling the loop
Multiple Subtraction Quiz
SubtractionQuiz.py, generates just one question for each
run. How do you write the code to generate five questions?
The program that generates five questions and, after a
student answers all of them, reports the number of correct
answers. The program also displays the time spent on the
test, as shown in the sample run.
What is 2 - 0? 2
You are correct!
What is 9 - 6? 3
You are correct!
What is 7 - 0? 7
You are correct!
What is 2 - 0? 2
You are correct!
What is 4 - 2? 2
You are correct!
Correct count is 5 out of 5
Test time is 15 seconds
Controlling a Loop with User
Confirmation
If you want the user to decide whether to take another
question, you can offer a user confirmation. The template of
the program can be coded as follows:
continueLoop = 'Y'
while continueLoop == ‘Y’:
# Execute the loop body once
...
# Prompt the user for confirmation
continueLoop = input("Enter Y to continue and N to
quit: ")
Controlling a Loop with a Sentinel
Value
Another common technique for controlling a loop is to
designate a special input value, known as a sentinel value,
which signifies the end of the input. A loop that uses a
sentinel value in this way is called a sentinel-controlled loop.
data = eval(input("Enter an integer (the input ends " +
"if it is 0): "))
# Keep reading data until the input is 0
sum = 0
while data != 0:
sum += data
data = eval(input("Enter an integer (the input ends " +
"if it is 0): "))
print("The sum is", sum)
Input and Output Redirections
if you have a lot of data to enter, You can store the data in a
text file (e.g. input.txt) and run the program by using the
following command:
python SentinelValue.py < input.txt
This command is called input redirection. Instead of having
the user type the data from the keyboard at runtime, the
program takes the input from the file input.txt.
output redirection can send the output to a file instead of
displaying it on the screen. The command for output
redirection is:
python Script.py > output.txt
Examples
How many times are the following loop bodies repeated? What is
the printout of each loop?
i = 1 i = 1 i = 1
while i < 10: while i < 10: while i < 10:
if i % 2 == 0: if i % 2 == 0: if i % 2 == 0:
print(i) print(i) print(i)
i += 1 i += 1
Show the errors in the following code:
count = 0 count = 0 count = 0
while count < 100: while count < 100: while count < 100:
print(count) print(count) count += 1
count -= 1
The for Loop
A Python for loop iterates through each value in a sequence.
Often you know exactly how many times the loop body needs to
be executed, so a control variable can be used to count the
executions. A loop of this type is called a counter-controlled loop.
i = initialValue # Initialize loop-control variable
while i < endValue:
# Loop body
...
i += 1 # Adjust loop-control variable
A for loop can be used to simplify the preceding loop:
for i in range(initialValue, endValue):
# Loop body
In general, the syntax for var in sequence:
of a for loop is: # Loop body
The function range
The function range(a, b) returns the sequence of integers
a, a + 1, ..., b - 2, and b - 1.
range(a) is the same as range(0, a).
k is used as step value in range(a, b, k). The first number
in the sequence is a. Each successive number in the
sequence will increase by the step value k. b is the limit. The
last number in the sequence must be less than b.
>>> for v in range(3, 9, 2):
>>> for v in range(4, 8):
... print(v)
... print(v)
...
... >>> for v in range(5, 1, -1):
3
4 ... print(v)
5
5 ...
7
6 5
>>>
7 4
>>> 3
2
Examples
Count the number of iterations in the following loops:
count = 0 for count in range(n):
while count < n: print(count)
count += 1
count = 5 count = 5
while count < n: while count < n:
count += 1 count = count + 3
Nested Loops
A loop can be nested inside another loop.
Nested loops consist of an outer loop and one or more inner
loops. Each time the outer loop is repeated, the inner loops
are reentered and started anew.
Ex: write a program that uses nested for loops to display a
multiplication table.
MultiplicationTable.py
print(" Multiplication Table")
# Display the number title
print(" |", end = '')
for j in range(1, 10):
print(" ", j, end = '')
print() # Jump to the new line
print("——————————————————————————————————————————")
# Display table body
for i in range(1, 10):
print(i, "|", end = '')
for j in range(1, 10):
# Display the product and align properly
print(format(i * j, "4d"), end = '')
print() # Jump to the new line
Examples
Show the output of the following programs
Keywords break and continue
The break and continue keywords provide additional
controls to a loop.
You can use the keyword break in a loop to immediately
terminate a loop.
sum = 0
number = 0
while number < 20:
number += 1
sum += number
if sum >= 100:
break
print("The number is", number)
print("The sum is", sum)
The number is 14
The sum is 105
Keywords break and continue
You can also use the continue keyword in a loop. When it is
encountered, it ends the current iteration and program control
goes to the end of the loop body
sum = 0
number = 0
while number < 20:
number += 1
if number == 10 or number == 11:
continue
sum += number
print("The sum is", sum)
The sum is 189
Displaying Prime Numbers
An integer greater than 1 is prime if its only positive divisor is 1
or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6,
8, and 9 are not.
Write a program that displays the first fifty prime numbers in
five lines, each containing ten numbers.
>>>
The first 50 prime numbers are
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
PROGRAMMING EXERCISES
Q1: Write a program that prompts the user to enter the
number of students and each student’s score, and displays
the highest score. Assume that the input is stored in a file
named score.txt, and the program obtains the input from the
file.
Q2: Use nested loops that display the following patterns in
four separate programs:
PROGRAMMING EXERCISES
Q3: Write a program that lets the user enter the loan amount
and loan period in number of years and displays the monthly
and total payments for each interest rate starting from 5% to
8%, with an increment of 1/8. Here is a sample run:
M = P * ( J / (1 - (1 + J)-N)). Follow the steps below for a
detailed guide to using this formula, or refer to this quick
explanation of each variable:
M = payment amount
P = principal, meaning the amount of money borrowed
J = effective interest rate. Note that this is usually not the
annual interest rate; see below for an explanation.
N = total number of payments
http://www.hughcalc.org/formula.php