Chapter5 CPIT110 v2 Loops
Chapter5 CPIT110 v2 Loops
Chapter5 CPIT110 v2 Loops
Loops
CPIT 110 (Problem-Solving and Programming)
Programs
• Program 1: Subtraction Quiz
• Program 2: Guessing Game
• Program 3: Multiple Subtraction Quiz
• Program 4: Advanced Multiple Subtraction Quiz
• Program 5: Sentinel Value
• Program 6: Multiplication Table
• Program 7: Finding the GCD
• Program 8: Predicting The Future Tuition
• Program 9: Prime Number
3
Check Points
• Section 5.2 • Section 5.4 ◦ #20
◦ #1 ◦ #10 ◦ #21
◦ #2 ◦ #11 ◦ #22
◦ #3 ◦ #12
◦ #4 ◦ #13
• Section 5.3 ◦ #14
◦ #5 ◦ #15
◦ #6 ◦ #16
◦ #7 • Section 5.7
◦ #8 ◦ #17
◦ #9 ◦ #18
◦ #19
4
Objectives
• To write programs for executing statements repeatedly by using a while loop (5.2).
• To develop loops following the loop design strategy (5.2.1-5.2.3).
• To control a loop with the user’s confirmation (5.2.4).
• To control a loop with a sentinel value (5.2.5).
• To use for loops to implement counter-controlled loops (5.3).
• To write nested loops (5.4).
• To learn the techniques for minimizing numerical errors (5.5).
• To learn loops from a variety of examples (GCD, FutureTuition, MonteCarloSimulation,
PrimeNumber) (5.6, 5.8).
• To implement program control with break and continue (5.7).
5
5.1. Motivations
▪ Loops
6
Motivations
• Suppose that you need to display a string (e.g., Programming is
fun!) 100 times.
• It would be tedious to type the statement 100 times:
1 print("Programming is fun!")
2 print("Programming is fun!")
3 print("Programming is fun!")
... ... 100
98 print("Programming is fun!") times
99 print("Programming is fun!")
100 print("Programming is fun!")
5.1 7
Motivations
• Solution:
◦ Python provides a powerful construct called a loop.
◦ A loop controls how many times an operation (or a sequence of
operations) is performed.
◦ By using a loop statement, you don’t have to code the print
statement a hundred times.
◦ You simply tell the computer to display a string that number of
times.
◦ The loop statement can be written as follows:
1 count = 0 Run
2 while count < 100:
3 print("Programming is fun!") The loop statement
4 count = count + 1
5.1 8
Motivations
• Solution:
1 count = 0 Run
2 while count < 100:
3 print("Programming is fun!")
4
The loop body
count = count + 1
• Details:
◦ The variable count is initially 0.
◦ The loop checks whether count < 100 is True.
▪ If so, the loop body is executed.
▪ "Programming is fun!" is printed.
▪ Then, count is incremented by 1 (count = count + 1).
◦ When count < 100 is False, the loop will terminate
▪ and the next statement after the loop statement is executed.
5.1 9
Loops
• A loop is a construct that controls the repeated execution of a
block of statements.
• The concept of looping is fundamental to programming.
• Python provides two types of loop statements:
◦ while loops
▪ The while loops is a condition-controlled loop.
▪ it is controlled by a True/False condition.
◦ for loops
▪ The for loop is a count-controlled loop.
▪ It repeats a specified number of times.
5.1 10
5.2. The while Loop
▪ Trace while Loop
▪ Infinite Loop
▪ Program 1: Subtraction Quiz
▪ Program 2: Guessing Game
▪ Loop Design Strategies
▪ Program 3: Multiple Subtraction Quiz
▪ Controlling a Loop with User Confirmation
▪ Program 4: Advanced Multiple Subtraction Quiz
▪ Controlling a Loop with a Sentinel Value
▪ Program 5: Sentinel Value
▪ Check Point #1 - #4
11
The while Loop
• 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)
5.2 12
The while Loop
• The syntax for the while loop is:
while loop-continuation-condition:
# Loop body
Statement(s)
5.2 13
The while Loop
• The loop that displays Programming is fun! 100 times is an
example of a while loop.
1 count = 0 loop-continuation-condition
2 while count < 100:
3 print("Programming is fun!")
loop body
4 count = count + 1
5.2 14
Trace while Loop
count → 0
1 count = 0
2 while count < 2:
Initialize count
3 print("Programming is fun!")
4 count = count + 1
5 print("Done")
5.2 1 of 9 15
Trace while Loop
count → 0
1 count = 0
2 while count < 2:
(count < 2) is True
3 print("Programming is fun!")
4 count = count + 1
5 print("Done")
5.2 2 of 9 16
Trace while Loop
count → 0
1 count = 0
2 while count < 2: Print Programming is
3 print("Programming is fun!") fun!
4 count = count + 1
5 print("Done")
Programming is fun!
5.2 3 of 9 17
Trace while Loop
count → 1
1 count = 0
2 while count < 2: Increase count by 1
3 print("Programming is fun!") count is 1 now
4 count = count + 1
5 print("Done")
Programming is fun!
5.2 4 of 9 18
Trace while Loop
count → 1
1 count = 0
2 while count < 2: (count < 2) is still True
3 print("Programming is fun!") since count is 1
4 count = count + 1
5 print("Done")
Programming is fun!
5.2 5 of 9 19
Trace while Loop
count → 1
1 count = 0
2 while count < 2: Print Programming is
3 print("Programming is fun!") fun!
4 count = count + 1
5 print("Done")
Programming is fun!
Programming is fun!
5.2 6 of 9 20
Trace while Loop
count → 2
1 count = 0
2 while count < 2: Increase count by 1
3 print("Programming is fun!") count is 2 now
4 count = count + 1
5 print("Done")
Programming is fun!
Programming is fun!
5.2 7 of 9 21
Trace while Loop
count → 2
1 count = 0
2 while count < 2: (count < 2) is False
3 print("Programming is fun!") since count is 2 now
4 count = count + 1
5 print("Done")
Programming is fun!
Programming is fun!
5.2 8 of 9 22
Trace while Loop
count → 2
Programming is fun!
Programming is fun!
Done
5.2 9 of 9 23
The while Loop
• Here is another example illustrating how a loop works:
1 sum = 0 Run
2 i = 1
3 while i < 10:
4 sum = sum + i
5 i = i + 1
6 print("sum is", sum) # sum is 45
• Details:
◦ if i < 10 is True, the program adds i to sum.
◦ The variable i is initially set to 1.
▪ Then it is incremented to 2, 3, and so on, up to 10.
◦ When i is 10, i < 10 is False, and the loop exits.
◦ So the sum is 1 + 2 + 3 + … + 9 = 45.
5.2 24
Infinite Loop
• Suppose the loop is mistakenly written as follows:
1 sum = 0 Run
2 i = 1
3 while i < 10:
4 sum = sum + i
5 i = i + 1
6 print("sum is", sum) # sum is 45
• Details:
◦ Note that the entire loop body must be indented inside the loop.
◦ Here the statement i = i + 1 is not in the loop body.
◦ This loop is infinite, because i is always 1 and i < 10 will always be
True.
5.2 25
Note
• Make sure that the loop-continuation-condition eventually
becomes False.
◦ So that the loop will terminate.
• A common programming error involves infinite loops.
◦ The loop runs forever.
• If your program takes an unusual long time to run and does not
stop, it may have an infinite loop.
• In PyCharm, click the small in the bottom
left corner.
◦ This will stop the execution of the program.
5.2 26
Caution
• New programmers often make the mistake of executing a loop one
extra time or one less time.
• This kind of mistake is commonly known as the off-by-one error.
• For example:
1 count = 0
2 while count <= 100:
3 print("Programming is fun!")
4 print(count)
5 count = count + 1
What is 4 - 3? 4 <Enter>
Wrong answer. Try again. What is 4 - 3? 5 <Enter>
Wrong answer. Try again. What is 4 - 3? 1 <Enter>
You got it!
5.2 Program 1 28
Subtraction Quiz
Phase 1: Problem-solving
Design your algorithm:
1. Generate two single-digit integers for number1 and number2.
▪ Example: number1 = 4 and number2 = 3
2. If number1 < number2, swap number1 with number2.
▪ Example: make number1 = 3 and number2 = 4
3. Ask the user to answer a question (answer)
▪ Example: “What is 4 - 3 ?”
4. Make a while loop:
▪ Condition of the loop is if the answer is wrong (number1 - number2 != answer)
▪ If the answer is wrong, we should:
➢ Ask the user to answer the question (answer) again.
What is 6 - 3? 1 <Enter>
Wrong answer. Try again. What is 6 - 3? 2 <Enter>
Wrong answer. Try again. What is 6 - 3? 4 <Enter>
Wrong answer. Try again. What is 6 - 3? 3 <Enter>
You got it!
What is 7 - 4? 99 <Enter>
Wrong answer. Try again. What is 7 - 4? 5 <Enter>
Wrong answer. Try again. What is 7 - 4? 9 <Enter>
Wrong answer. Try again. What is 7 - 4? 8 <Enter>
Wrong answer. Try again. What is 7 - 4? 7 <Enter>
Wrong answer. Try again. What is 7 - 4? 3 <Enter>
You got it!
5.2 Program 1 31
Guessing Game
Program 2
Write a program that randomly generates a number between 0
and 100, inclusive. The program will repeatedly ask the user to
guess the number until the user gets the number correct. At each
wrong answer, the program tells the user if the guess is too low
or too high.
5.2 Program 2 32
Guessing Game
Phase 1: Problem-solving
• This is the famous number guessing game.
• What is the normal first guess?
◦ 50
• Why?
◦ Because no matter the result (too high or too low), the number of
possible answers left is divided in half!
▪ If the guess is too high, you know the answer is in between 0 and 49.
▪ If the guess is too low, you know the answer is in between 51 and 100.
▪ So you can eliminate half of the numbers from consideration.
5.2 Program 2 33
Guessing Game
Phase 1: Problem-solving
• So are we ready to code?
◦ NO!
• We must THINK before coding.
• Think:
◦ How would you solve the problem without a program?
◦ You need a random number between 0 and 100.
◦ You need to ask the user to enter a guess.
◦ You need to compare the guess with the random number.
5.2 Program 2 34
Guessing Game
Phase 1: Problem-solving
• Good idea to code incrementally when using loops
• Meaning:
◦ Do not write the looping structure immediately.
◦ First, try to just write the logic of the program, but without using
loops.
▪ So just write the code for one "loop", one iteration.
◦ Then, write the code for the loop structure.
◦ Think of the following code as an “initial draft”.
5.2 Program 2 35
Guessing Game
Phase 2: Implementation (1st Draft)
LISTING 5.2 GuessNumberOneTime.py
1 import random Run
2
3 # Generate a random number to be guessed
4 number = random.randint(0, 100)
5
6 print("Guess a magic number between 0 and 100")
7
8 # Prompt the user to guess the number
9 guess = eval(input("Enter your guess: "))
10
11 if guess == number:
12 print("Yes, the number is " + str(number))
13 elif guess > number:
14 print("Your guess is too high")
15 else:
16 print("Your guess is too low")
5.2 Program 2 36
Guessing Game
Phase 1: Problem-solving
• When this program runs, it prompts the user to enter a guess
only once.
Guess a magic number between 0 and 100
Enter your guess: 50 <Enter>
Your guess is too high
• To let the user enter a guess repeatedly, you can change the
code in lines 9–16 to create a loop, as follows:
1 while True:
2 # Prompt the user to guess the number
3 guess = eval(input("Enter your guess: "))
4
5 if guess == number:
6 print("Yes, the number is " + str(number))
7 elif guess > number:
8 print("Your guess is too high")
9 else:
10 print("Your guess is too low")
5.2 Program 2 37
Guessing Game
Phase 2: Implementation (2nd Draft)
GuessNumberInfiniteTime.py
1 import random Run
2
3 # Generate a random number to be guessed
4 number = random.randint(0, 100)
5
6 print("Guess a magic number between 0 and 100")
7
8 while True:
9 # Prompt the user to guess the number
10 guess = eval(input("Enter your guess: "))
11
12 if guess == number:
13 print("Yes, the number is " + str(number))
14 elif guess > number:
15 print("Your guess is too high")
16 else:
17 print("Your guess is too low")
5.2 Program 2 38
Guessing Game
Phase 1: Problem-solving
• This loop repeatedly prompts the user to enter a guess.
Guess a magic number between 0 and 100
Enter your guess: 25 <Enter>
Your guess is too low
Enter your guess: 39 <Enter>
Yes, the number is 39
Enter your guess: 42 <Enter>
Your guess is too high
Enter your guess: ...
• However, the loop doesn’t end even if the user entered the
correct guess.
• This is because the condition of the loop is always True.
• So the loop still needs to terminate.
◦ When the guess is finally correct, the loop should exit.
5.2 Program 2 39
Guessing Game
Phase 1: Problem-solving
• So what is the loop condition?
while (guess != number)
◦ So if the guess is not the same as the random number, continue
the while loop.
• So, revise the loop as follows:
1 guess = -1 # Initial value that doesn't meet the loop condition
2 while guess != number:
3 # Prompt the user to guess the number
4 guess = eval(input("Enter your guess: "))
5
6 if guess == number:
7 print("Yes, the number is", number)
8 elif guess > number:
9 print("Your guess is too high")
10 else:
11 print("Your guess is too low")
5.2 Program 2 40
Guessing Game
Phase 2: Implementation (Final)
LISTING 5.3 GuessNumber.py
1 import random Run
2
3 # Generate a random number to be guessed
4 number = random.randint(0, 100)
5
6 print("Guess a magic number between 0 and 100")
7
8 guess = -1 # Initial value that doesn't meet the loop condition
9 while guess != number:
10 # Prompt the user to guess the number
11 guess = eval(input("Enter your guess: "))
12
13 if guess == number:
14 print("Yes, the number is", number)
15 elif guess > number:
16 print("Your guess is too high")
17 else:
18 print("Your guess is too low")
5.2 Program 2 41
Guessing Game
Trace The Program Execution
Guess a magic number between 0 and 100
Enter your guess: 50 <Enter>
Your guess is too high
Enter your guess: 25 <Enter>
Your guess is too low
Enter your guess: 42 <Enter>
Your guess is too high
Enter your guess: 39 <Enter>
Yes, the number is 39
5.2 Program 2 42
Guessing Game
Discussion
• The program generates the random number in line 4.
• Then, it prompts the user to enter a guess continuously in a
loop (lines 9–18).
• For each guess, the program determines whether the user’s
number is correct, too high, or too low (lines 13–18).
• When the guess is correct, the program exits the loop (line 9).
• Note that guess is initialized to -1.
◦ This is to avoid initializing it to a value between 0 and 100, because
that could be the number to be guessed.
5.2 Program 2 43
Loop Design Strategies
• Coding a correct loop is challenging for new programmers.
• Therefore, three steps are recommended:
◦ Step 1: Identify the statements that need to be repeated.
◦ Step 2: Wrap these statements in a loop (Infinite loop) like this:
while True:
Statements
5.2 44
Multiple Subtraction Quiz
Program 3
Write a program to randomly generate five subtraction questions
and ask the user for the answer to each. Count how many the
user got correct, and display the total time spent, by the user,
answering the five questions.
What is 1 - 1? 0 <Enter>
You are correct!
What is 7 - 2? 5 <Enter>
You are correct!
What is 9 - 3? 4 <Enter>
Your answer is wrong.
9 - 3 is 6
What is 6 - 6? 0 <Enter>
You are correct!
What is 9 - 6? 2 <Enter>
Your answer is wrong.
9 - 6 is 3
5.2 Program 3 45
Multiple Subtraction Quiz
Phase 1: Problem-solving
• Use the loop design strategy:
◦ First, identify the statements that need to be repeated.
➢ The statements for randomly generating two numbers.
➢ Asking the user for the answer to the subtraction question.
➢ Grading the question.
▪ Comparing user answer to the real answer.
◦ Second, wrap these statements inside a loop.
◦ Finally, add a loop control variable and an appropriate loop-
continuation-condition that will execute the loop five times.
5.2 Program 3 46
Multiple Subtraction Quiz
Phase 2: Implementation
LISTING 5.4 SubtractionQuizLoop.py
1 import random
2 import time
3
4 correctCount = 0 # Count the number of correct answers
5 count = 0 # Count the number of questions
6 NUMBER_OF_QUESTIONS = 5 # Constant Run
7
8 startTime = time.time() # Get start time
9
10 while count < NUMBER_OF_QUESTIONS:
11 # 1. Generate two random single-digit integers
12 number1 = random.randint(0, 9)
13 number2 = random.randint(0, 9)
14
15 # 2. If number1 < number2, swap number1 with number2
16 if number1 < number2:
17 number1, number2 = number2, number1
18
5.2 Program 3 47
Multiple Subtraction Quiz
Phase 2: Implementation
LISTING 5.4 SubtractionQuizLoop.py
19 # 3. Prompt the student to answer "what is number1 - number2?"
20 answer = eval(input("What is " + str(number1) + " - " +
21 str(number2) + "? "))
22
23 # 5. Grade the answer and display the result
24 if number1 - number2 == answer: Run
25 print("You are correct!")
26 correctCount += 1
27 else:
28 print("Your answer is wrong.\n", number1, "-",
29 number2, "should be", (number1 - number2))
30
31 # Increase the count
32 count += 1
33
34 endTime = time.time() # Get end time
35 testTime = int(endTime - startTime) # Get test time
36 print("Correct count is", correctCount, "out of",
37 NUMBER_OF_QUESTIONS, "\nTest time is", testTime, "seconds")
5.2 Program 3 48
Multiple Subtraction Quiz
Discussion
• The program uses the control variable count to control the
execution of the loop.
◦ count is initially 0 (line 5)
◦ count is increased by 1 in each iteration (line 32).
◦ A subtraction question is displayed and processed in each
iteration.
• The program obtains the time before the test starts (line 8) and
the time after the test ends (line 34).
◦ Then, it computes the test time in seconds (line 35).
• The program displays the correct count and test time after all
the quizzes have been taken (lines 36–37).
5.2 Program 3 49
Controlling a Loop with User
Confirmation
• The preceding example (Program 3) executes the loop five
times.
• 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: ")
5.2 50
Advanced Multiple Subtraction Quiz
Program 4
Rewrite Program 3 with user confirmation to let the user decide
whether to advance to the next question.
What is 6 - 1? 5 <Enter>
You are correct!
Enter Y to continue and N to quit: Y <Enter>
What is 8 - 0? 6 <Enter>
Your answer is wrong.
8 - 0 should be 8
Enter Y to continue and N to quit: Y <Enter>
What is 8 - 3? 5 <Enter>
You are correct!
Enter Y to continue and N to quit: N <Enter>
5.2 Program 4 51
Advanced Multiple Subtraction Quiz
Phase 1: Problem-solving
• Use the template of controlling a loop with user confirmation:
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: ")
5.2 Program 4 52
Advanced Multiple Subtraction Quiz
Phase 2: Implementation
SubtractionQuizLoopUserConfirmation.py
1 import random Run
2 import time
3
4 correctCount = 0 # Count the number of correct answers
5 count = 0 # Count the number of questions
6
7 startTime = time.time() # Get start time
8
9 continueLoop = 'Y' # User confirmation flag
10 while continueLoop == 'Y':
11 # 1. Generate two random single-digit integers
12 number1 = random.randint(0, 9)
13 number2 = random.randint(0, 9)
14
15 # 2. If number1 < number2, swap number1 with number2
16 if number1 < number2:
17 number1, number2 = number2, number1
18
19 # 3. Prompt the student to answer "what is number1 - number2?“
20 answer = eval(input("What is " + str(number1) + " - " +
21 str(number2) + "? "))
5.2 Program 4 53
Advanced Multiple Subtraction Quiz
Phase 2: Implementation
SubtractionQuizLoopUserConfirmation.py
22 Run
23 # 5. Grade the answer and display the result
24 if number1 - number2 == answer:
25 print("You are correct!")
26 correctCount += 1
27 else:
28 print("Your answer is wrong.\n", number1, "-",
29 number2, "should be", (number1 - number2))
30
31 # Increase the count
32 count += 1
33
34 # Prompt the user for confirmation
35 continueLoop = input("Enter Y to continue and N to quit: ")
36 print() # To insert a new line
37
38 endTime = time.time() # Get end time
39 testTime = int(endTime - startTime) # Get test time
40 print("Correct count is", correctCount, "out of",
41 count, "\nTest time is", testTime, "seconds")
5.2 Program 4 54
Controlling a Loop with a Sentinel Value
• Often the number of times a loop is executed is not predetermined.
• Another common technique for controlling a loop is by choosing a
special value when reading and processing user input.
• This special input value is known as a sentinel value.
• The sentinel value signifies the end of the input.
• A loop that uses a sentinel value in this way is called a sentinel-
controlled loop.
• Example:
➢ Ask the user to keep inputting as many integer values as they want.
➢ Tell them that the loop will stop once the value -1 is entered.
➢ Therefore, -1 would be the sentinel value.
5.2 55
Sentinel Value
Program 5
Write a program that will sum up all user inputted values. The
user can keep inputting values for as long as the user wishes. If
the user enters "0", this means the end of the input. Your
program should display the sum to the user.
5.2 Program 5 56
Sentinel Value
Phase 1: Problem-solving
• Use the loop design strategy:
◦ First, identify the statements that need to be repeated.
➢ Ask the user for a value (data).
▪ data = eval(input("Enter an integer ..."))
➢ Add it to the variable sum.
▪ sum += data
◦ Second, wrap these statements inside a loop.
◦ Finally, add a loop control variable and an appropriate loop-
continuation-condition which will be data != 0 (the sentinel value).
5.2 Program 5 57
Sentinel Value
Phase 2: Implementation
LISTING 5.5 SentinelValue.py
1 data = eval(input("Enter an integer (the input exits " + Run
2 "if the input is 0): "))
3
4 # Keep reading data until the input is 0
5 sum = 0
6 while data != 0:
7 sum += data
8
9 data = eval(input("Enter an integer (the input exits " +
10 "if the input is 0): "))
11
12 print("The sum is", sum)
5.2 Program 5 58
Sentinel Value
Trace The Program Execution
Enter an integer (the input ends if it is 0): 2 <Enter>
Enter an integer (the input ends if it is 0): 3 <Enter>
Enter an integer (the input ends if it is 0): 4 <Enter>
Enter an integer (the input ends if it is 0): 0 <Enter>
The sum is 9
5.2 Program 5 59
Sentinel Value
Discussion
• If data is not 0, it is added to the sum (line 7) and the next item
of input data is read (lines 9–10).
• If data is 0, the loop body is no longer executed, and the while
loop terminates.
• The input value 0 is the sentinel value for this loop.
• Note that if the first input read is 0, the loop body never
executes, and the resulting sum is 0.
Enter an integer (the input ends if it is 0): 0 <Enter>
The sum is 0
5.2 Program 5 60
Caution
• Don’t use floating-point values for equality checking in a loop
control.
• Why?
◦ Since those values are approximated, they could lead to imprecise
counter values.
• Consider the following code for computing 1 + 0.9 + 0.8 + ... +
0.1:
1 item = 1
2 sum = 0
3 while item != 0: # No guarantee item will be 0
4 sum += item
5 item -= 0.1
6 print(sum)
5.2 61
Caution
• Consider the following code for computing 1 + 0.9 + ... + 0.1:
1 item = 1 Iteration 1 →
Iteration 2 →
0.9
0.8
item 1
1.9
sum
2 sum = 0 Iteration 3 → 0.7000000000000001 2.7
Iteration 4 → 0.6000000000000001 3.4000000000000004
3 while item != 0: Iteration 5 → 0.5000000000000001 4.0
4 sum += item Iteration 6 →
Iteration 7 →
0.40000000000000013
0.30000000000000016
4.5
4.9
5 item -= 0.1 Iteration 8 → 0.20000000000000015 5.2
Iteration 9 → 0.10000000000000014 5.4
6 print(sum) Iteration 10 → 0.00000000000000001 5.500000000000001
➢ The variable item starts with 1 and is reduced by 0.1 every time the loop
body is executed.
➢ The loop should terminate when item becomes 0.
➢ However, there is no guarantee that item will be exactly 0, because the
floating-point arithmetic is approximated.
▪ 0.00000000000000001 != 0 → True
➢ This loop seems okay on the surface, but it is actually an infinite loop.
5.2 62
Check Point
#1
Analyze the following code. Is count < 100 always True, always
False, or sometimes True or sometimes False at Point A, Point B,
and Point C?
1 count = 0
2 while count < 100:
3 # Point A
4 print("Programming is fun!")
5 count += 1
6 # Point B
7
8 # Point C
➢ Answer:
➢ Point A: always True
➢ Point B: sometimes False (Only one time)
➢ Point C: always False
5.2 63
Check Point
#2
What is wrong if guess is initialized to 0 in line 8 in the following code?
LISTING 5.3 GuessNumber.py
1 import random
2 Run
3 # Generate a random number to be guessed
4 number = random.randint(0, 100)
5
6 print("Guess a magic number between 0 and 100")
7
8 guess = -1 # Initial value that doesn't meet the loop condition
9 while guess != number:
10 # Prompt the user to guess the number
11 guess = eval(input("Enter your guess: "))
12
13 if guess == number:
14 print("Yes, the number is", number)
15 elif guess > number:
16 print("Your guess is too high")
17 else:
18 print("Your guess is too low")
1 i = 1 1 i = 1 1 i = 1
2 while i < 10: 2 while i < 10: 2 while i < 10:
3 if i % 2 == 0: 3 if i % 2 == 0: 3 if i % 2 == 0:
4 print(i) 4 print(i) 4 print(i)
5 5 i += 1 5 i += 1
(a) (b) (c)
2
4
6
8
Empty Empty
5.2 65
Check Point
#4
Suppose the input is 2 3 4 5 0 (one number per line). What is the
output of the following code?
1 number = eval(input("Enter an integer: ")) Run
2 max = number
3
4 while number != 0:
5 number = eval(input("Enter an integer: "))
6 if number > max:
7 max = number
8
9 print("max is", max)
10 print("number", number)
5.2 66
5.3. The for Loop
▪ Trace for Loop
▪ The range Function
▪ range(a, b)
▪ range(a)
▪ range(a, b, k)
▪ Check Point #5 - #9
67
The for Loop
• Often you will use a while loop to iterate a certain number of
times.
• A loop of this type is called a counter-controlled loop.
• In general, the loop can be written as follows:
i = initialValue # Initialize loop-control variable
while i < endValue:
# Loop body
...
i += 1 # Adjust loop-control variable
5.3 68
The for Loop
i = initialValue # Initialize loop-control variable
while i < endValue:
# Loop body
...
i += 1 # Adjust loop-control variable
5.3 69
The for Loop
Flowchart
• Flowchart for a generic for loop:
for i in range(0,5):
print(i)
0
1
2
3
4
5.3 71
Trace for Loop
1 print("Start ...")
2 for i in range(0,5):
Print “Start ...”
3 print("i =", i)
4 print("... End")
Start ...
5.3 1 of 12 72
Trace for Loop
Range (0, 5) → [0,1,2,3,4]
i→ 0
1 print("Start ...")
2 for i in range(0,5): Loop 5 times.
3 print("i =", i) Loop #1
4 print("... End")
Start ...
5.3 2 of 12 73
Trace for Loop
Range (0, 5) → [0,1,2,3,4]
i→ 0
1 print("Start ...")
2 for i in range(0,5):
Print “i = 0”
3 print("i =", i)
4 print("... End")
Start ...
i = 0
5.3 3 of 12 74
Trace for Loop
Range (0, 5) → [0,1,2,3,4]
i→ 1
1 print("Start ...")
2 for i in range(0,5):
Loop #2
3 print("i =", i)
4 print("... End")
Start ...
i = 0
5.3 4 of 12 75
Trace for Loop
Range (0, 5) → [0,1,2,3,4]
i→ 1
1 print("Start ...")
2 for i in range(0,5):
Print “i = 1”
3 print("i =", i)
4 print("... End")
Start ...
i = 0
i = 1
5.3 5 of 12 76
Trace for Loop
Range (0, 5) → [0,1,2,3,4]
i→ 2
1 print("Start ...")
2 for i in range(0,5):
Loop #3
3 print("i =", i)
4 print("... End")
Start ...
i = 0
i = 1
5.3 6 of 12 77
Trace for Loop
Range (0, 5) → [0,1,2,3,4]
i→ 2
1 print("Start ...")
2 for i in range(0,5):
Print “i = 2”
3 print("i =", i)
4 print("... End")
Start ...
i = 0
i = 1
i = 2
5.3 7 of 12 78
Trace for Loop
Range (0, 5) → [0,1,2,3,4]
i→ 3
1 print("Start ...")
2 for i in range(0,5):
Loop #4
3 print("i =", i)
4 print("... End")
Start ...
i = 0
i = 1
i = 2
5.3 8 of 12 79
Trace for Loop
Range (0, 5) → [0,1,2,3,4]
i→ 3
1 print("Start ...")
2 for i in range(0,5):
Print “i = 3”
3 print("i =", i)
4 print("... End")
Start ...
i = 0
i = 1
i = 2
i = 3
5.3 9 of 12 80
Trace for Loop
Range (0, 5) → [0,1,2,3,4]
i→ 4
1 print("Start ...")
2 for i in range(0,5):
Loop #5
3 print("i =", i)
4 print("... End")
Start ...
i = 0
i = 1
i = 2
i = 3
5.3 10 of 12 81
Trace for Loop
Range (0, 5) → [0,1,2,3,4]
i→ 4
1 print("Start ...")
2 for i in range(0,5):
Print “i = 4”
3 print("i =", i)
4 print("... End")
Start ...
i = 0
i = 1
i = 2
i = 3
i = 4
5.3 11 of 12 82
Trace for Loop
Range (0, 5) → [0,1,2,3,4]
i→ 4
1 print("Start ...")
2 for i in range(0,5):
Print “... End”
3 print("i =", i)
4 print("... End")
Start ...
i = 0
i = 1
i = 2
i = 3
i = 4
... End
5.3 12 of 12 83
The range Function
• The range() function returns a sequence of integer numbers,
starting from 0 by default, and increments by 1 (by default),
and ends at a specified number.
• Syntax:
range(start, stop, step)
◦ start: an integer number specifying at which position to start.
Default is 0.
◦ stop: an integer number specifying at which position to end.
◦ step: an integer number specifying the incrementation. Default is 1
• It has three versions:
◦ range(a)
◦ range(a, b)
◦ range(a, b, k)
5.3 84
range(a, b)
• The function range(a, b) returns the sequence of integers
a, a + 1, ..., b - 2, and b - 1.
• For example:
1 for v in range(4, 8):
2 print("v =", v)
v = 4
v = 5
v = 6
v = 7
5.3 85
range(a)
• The function range(a) is the same as range(0, a).
• For example:
1 for v in range(6):
2 print("v =", v)
v = 0
v = 1
v = 2
v = 3
v = 4
v = 5
5.3 86
range(a, b, k)
• 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.
• Example:
1 for v in range(3, 9, 2):
2 print("v =", v)
v = 3
v = 5
v = 7
◦ The step value in range (3, 9, 2) is 2, and the limit is 9. So, the sequence is 3, 5, and 7
5.3 87
range(a, b, k)
Count Backward
• The range(a, b, k) function can count backward if k is negative.
• In this case, the sequence is still a, a + k, a + 2k, and so on for a
negative k.
• The last number in the sequence must be greater than b.
• Example:
1 for v in range(5, 1, -1):
2 print("v =", v)
v = 5
v = 4
v = 3
v = 2
5.3 88
Note
• The numbers in the range function must be integers.
• For example, range(1.5, 8.5), range(8.5), or range(1.5, 8.5, 1)
would be wrong.
• Example:
1 for v in range(6.5):
2 print("v =", v)
for v in range(6.5):
TypeError: 'float' object cannot be interpreted as
an integer
5.3 89
Note
range(2) [0, 1]
range(2,3) [2]
range(2,-3) []
range(2, 2) []
range(1, 2, 2) [1]
range(2, 2, -1) []
5.3 90
Check Point
#5
Suppose the input is 2 3 4 5 0 (one number per line). What is the
output of the following code?
1 number = 0 Run
2 sum = 0
3
4 for count in range(5):
5 number = eval(input("Enter an integer: "))
6 sum += number
7
8 print("sum is", sum)
9 print("count is", count)
5.3 91
Check Point
#6
Can you convert any for loop to a while loop? List the advantages
of using for loops.
➢ Answers:
➢ Yes, we can convert any for loop to a while loop.
➢ Advantages:
▪ The number of repetitions is specified explicitly in advance.
▪ When using a while loop, programmers often forget to adjust the control
variable such as (i += 1). Using for loop can avoid this error.
5.3 92
Check Point
#7
Convert the following for loop statement to a while loop:
1 sum = 0
2 for i in range(1001):
sum = 500500
3 sum = sum + i
4 print("sum =", sum)
➢ Solution:
1 sum = 0
2 i = 0
3 while i < 1001:
sum = 500500
4 sum = sum + i
5 i += 1
6 print("sum =", sum)
5.3 93
Check Point
#8
Can you always convert any while loop into a for loop? Convert
the following while loop into a for loop.
1 i = 1
2 sum = 0
3 while sum < 10000:
4 sum = sum + i sum = 10011
5 i += 1
6 print("sum =", sum)
➢ Answers:
➢ No, we cannot always convert any while loop into a for loop
especially for the while loop that is not based on the counter
variable (counter-controlled loop).
1 sum = 0
2 for i in range(1, 142):
3 sum = sum + i sum = 10011
4 print("sum =", sum)
5.3 94
Check Point
#9
How many times are the following loop bodies repeated? What is
the printout of each loop?
1 count = 0 1 for count in range(n):
2 while count < n: 2 print(count)
3 count += 1 3
(a) (b)
n Times n Times
1 count = 5 1 count = 5
2 while count < n: 2 while count < n:
3 count += 1 3 count += 3
(c) (d)
(n – count) Times (The ceiling of (n - 5) / 3) Times
5.3 95
5.4. Nested Loops
▪ Trace Nested Loops
▪ Program 6: Multiplication Table
▪ Check Point #10 - #16
96
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.
Start
• Example: Outer Loop ----- x = 1 -----
1 print("Start") y = 4
Run y = 5
2 print()
3 ----- x = 2 -----
4 for x in range(1, 4): y = 4
5 print("----- x =", x, "-----") y = 5
6 for y in range(4, 6):
7 print("y =", y) ----- x = 3 -----
y = 4
8 print() y = 5
9
10 print("End") Inner Loop End
5.4 97
Trace Nested Loops
5.4 1 of 33 98
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Loop 3 times, and the sequence is [1, 2, 3].
So, the first item is 1. now i is 1. i j
1
1 for i in range(1, 4):
2 j = 0
3 while j < i:
4 print(j, end = " ")
5 j += 1
6 print()
7 print("Done")
5.4 2 of 33 99
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
j is 0 now i j
1
1 for i in range(1, 4): 0
2 j = 0
3 while j < i:
4 print(j, end = " ")
5 j += 1
6 print()
7 print("Done")
5.4 3 of 33 100
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
0 < 1 is True i j
1
1 for i in range(1, 4): 0
2 j = 0
3 while j < i:
4 print(j, end = " ")
5 j += 1
6 print()
7 print("Done")
5.4 4 of 33 101
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Print 0 and put a white space “ “ at the end. i j
1
1 for i in range(1, 4): 0
2 j = 0
3 while j < i:
4 print(j, end = " ")
5 j += 1
6 print()
7 print("Done")
5.4 5 of 33 102
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Increment j by 1. j is 1 now. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i:
4 print(j, end = " ")
5 j += 1
6 print()
7 print("Done")
5.4 6 of 33 103
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
1 < 1 is False. i j
Exit from the current loop (inner loop).
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i:
4 print(j, end = " ")
5 j += 1
6 print()
7 print("Done")
5.4 7 of 33 104
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Print a new line (\n) i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i:
4 print(j, end = " ")
5 j += 1
6 print()
7 print("Done")
5.4 8 of 33 105
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Update i to the next unused item in the
sequence. Now i is 2. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
5 j += 1
6 print()
7 print("Done")
5.4 9 of 33 106
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
j is 0 now i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print()
7 print("Done")
5.4 10 of 33 107
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
0 < 2 is True i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print()
7 print("Done")
5.4 11 of 33 108
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Print 0 and put a white space “ “ at the end. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print()
7 print("Done")
0
0
5.4 12 of 33 109
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Increment j by 1. j is 1 now. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done")
0
0
5.4 13 of 33 110
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
1 < 2 is True i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done")
0
0
5.4 14 of 33 111
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Print 1 and put a white space “ “ at the end. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done")
0
0 1
5.4 15 of 33 112
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Increment j by 1. j is 2 now. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
0
0 1
5.4 16 of 33 113
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
2 < 2 is False. i j
Exit from the current loop (inner loop).
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
0
0 1
5.4 17 of 33 114
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Print a new line (\n) i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
0
0 1
5.4 18 of 33 115
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Update i to the next unused item in the
sequence. Now i is 3. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
3
0
0 1
5.4 19 of 33 116
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
j is 0 now i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
3
0 0
0 1
5.4 20 of 33 117
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
0 < 3 is True i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
3
0 0
0 1
5.4 21 of 33 118
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Print 0 and put a white space “ “ at the end. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
3
0 0
0 1
0
5.4 22 of 33 119
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Increment j by 1. j is 1 now. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
3
0 0
0 1 1
0
5.4 23 of 33 120
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
1 < 3 is True i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
3
0 0
0 1 1
0
5.4 24 of 33 121
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Print 1 and put a white space “ “ at the end. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
3
0 0
0 1 1
0 1
5.4 25 of 33 122
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Increment j by 1. j is 2 now. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
3
0 0
0 1 1
0 1
2
5.4 26 of 33 123
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
2 < 3 is True i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
3
0 0
0 1 1
0 1
2
5.4 27 of 33 124
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
Print 2 and put a white space “ “ at the end. i j
1
1 for i in range(1, 4): 0
2 j = 0 1
3 while j < i: 2
4 print(j, end = " ")
0
5 j += 1
6 print() 1
7 print("Done") 2
3
0 0
0 1 1
0 1 2
2
5.4 28 of 33 125
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
i j
Increment j by 1. j is 3 now. 1
0
1 for i in range(1, 4): 1
2 j = 0 2
3 while j < i: 0
4 print(j, end = " ")
1
5 j += 1
6 print() 2
7 print("Done") 3
0
0 1
0 1 2
0 1 2
3
5.4 29 of 33 126
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
i j
3 < 3 is False. 1
Exit from the current loop (inner loop).
0
1 for i in range(1, 4): 1
2 j = 0 2
3 while j < i: 0
4 print(j, end = " ")
1
5 j += 1
6 print() 2
7 print("Done") 3
0
0 1
0 1 2
0 1 2
3
5.4 30 of 33 127
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
i j
Print a new line (\n) 1
0
1 for i in range(1, 4): 1
2 j = 0 2
3 while j < i: 0
4 print(j, end = " ")
1
5 j += 1
6 print() 2
7 print("Done") 3
0
0
1
0 1
0 1 2 2
3
5.4 31 of 33 128
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
i j
Is there any unused item in the sequence? No.
So, exit from the current loop (outer loop) 1
0
1 for i in range(1, 4): 1
2 j = 0 2
3 while j < i: 0
4 print(j, end = " ")
1
5 j += 1
6 print() 2
7 print("Done") 3
0
0
1
0 1
0 1 2 2
3
5.4 32 of 33 129
Trace Nested Loops
Range (1, 4) → [1,2,3]
Program Trace
i j
Print Done 1
0
1 for i in range(1, 4): 1
2 j = 0 2
3 while j < i: 0
4 print(j, end = " ")
1
5 j += 1
6 print() 2
7 print("Done") 3
0
0
1
0 1
0 1 2 2
Done 3
5.4 33 of 33 130
Multiplication Table
Program 6
Write a program that uses nested for loops to print out the 1
through 9 multiplication table.
Multiplication Table
| 1 2 3 4 5 6 7 8 9
-----------------------------------------
1 | 1 2 3 4 5 6 7 8 9
2 | 2 4 6 8 10 12 14 16 18
3 | 3 6 9 12 15 18 21 24 27
4 | 4 8 12 16 20 24 28 32 36
5 | 5 10 15 20 25 30 35 40 45
6 | 6 12 18 24 30 36 42 48 54
7 | 7 14 21 28 35 42 49 56 63
8 | 8 16 24 32 40 48 56 64 72
9 | 9 18 27 36 45 54 63 72 81
5.4 137
Check Point
#10
How many times is the print statement executed:
1 for i in range(10):
2 for j in range(i):
3 print(i * j)
➢ Solution:
◦ The outer loop runs 10 times
▪ From 0 to 9
◦ For each iteration, the inner loop runs from 0 to i
▪ First time i is 0, then i is 1, then 2, then 3, until i is 9
◦ Answer: 1 + 2 + 3 + … + 9 = 45 times
5.4 138
Check Point
#11
Show the output of the following Program Trace
programs. (Hint: Draw a table and list i j
the variables in the columns to trace 1 0
1
these programs.)
2 0
1 for i in range(1, 5): 1
2 j = 0 2
3 while j < i:
3 0
4 print(j, end = " ")
5 j += 1 1
2
(a)
3
4 0
0 0 1 0 1 2 0 1 2 3 1
2
3
4
5.4 139
Check Point
#12
Program Trace
1 i = 0 i j
2 while i < 5: 0
3 for j in range(i, 1, -1):
1
4 print(j, end = " ")
5 print("****") 2
6 i += 1 2
(B) 3
3
**** 2
**** 4
2 **** 4
3 2 **** 3
4 3 2 **** 2
5.4 140
Check Point Program Trace
#13 i
5
num
1
j
2 1
4 2
1 i = 5 8 3
2 while i >= 1: 16 4
3 num = 1 32 5
4 for j in range(1, i + 1): 4 1
5 print(num, end = "xxx")
2 1
6 num *= 2
4 2
7 print()
8 3
8 i -= 1
16 4
(c) 3 1
2 1
1xxx2xxx4xxx8xxx16xxx 4 2
1xxx2xxx4xxx8xxx 8 3
1xxx2xxx4xxx 2 1
1xxx2xxx 2 1
1xxx 4 2
1 1
2 1
5.4 141
Check Point Program Trace
#14 i
1
num
1
j
3 1
2 1
1 i = 1 3 1
2 while i <= 5: 5 2
3 num = 1 3 1
4 for j in range(1, i + 1): 3 1
5 print(num, end = "G")
5 2
6 num += 2
7 3
7 print()
4 1
8 i += 1
3 1
(d) 5 2
7 3
1G 9 4
1G3G 5 1
1G3G5G 3 1
1G3G5G7G 5 2
1G3G5G7G9G 7 3
9 4
11 5
5.4 142
Check Point Program Trace
#15 i
5
num
1
j
2 1
4 2
1 i = 5 8 3
2 while i >= 1: 16 4
3 num = 1 32 5
4 for j in range(1, i + 1): 4 1
5 num *= 2
2 1
6 print(num, end = "xxx")
4 2
7 print()
8 3
8 i -= 1
16 4
(e) 3 1
2 1
2xxx4xxx8xxx16xxx32xxx 4 2
2xxx4xxx8xxx16xxx 8 3
2xxx4xxx8xxx 2 1
2xxx4xxx 2 1
2xxx 4 2
1 1
2 1
5.4 143
Check Point Program Trace
#16 i
1
num
1
j
3 1
2 1
1 i = 1 3 1
2 while i <= 5: 5 2
3 num = 1 3 1
4 for j in range(1, i + 1): 3 1
5 num += 2
5 2
6 print(num, end = "G")
7 3
7 print()
4 1
8 i += 1
3 1
(f) 5 2
7 3
3G 9 4
3G5G 5 1
3G5G7G 3 1
3G5G7G9G 5 2
3G5G7G9G11G 7 3
9 4
11 5
5.4 144
5.5. Minimizing Numerical Errors
145
Minimizing Numerical Errors
• Using floating-point numbers in the loop-continuation-
condition may cause numeric errors.
• Numerical errors involving floating-point numbers are
inevitable.
• This section provides an example showing you how to minimize
such errors.
5.5 146
Minimizing Numerical Errors
Example
The following program sums a series that starts with 0.01 and
ends with 1.0. The numbers in the series will increment by 0.01,
as follows: 0.01 + 0.02 + 0.03 and so on.
LISTING 5.7 TestSum.py
5.5 147
Minimizing Numerical Errors
Example
• The result displayed is 49.5, but the correct result is 50.5.
• What went wrong?
◦ For each iteration in the loop, i is incremented by 0.01.
◦ When the loop ends, the i value is slightly larger than 1 (not exactly 1).
◦ This causes the last i value not to be added into sum.
• The fundamental problem is that the floating-point numbers are
represented by approximation.
5.5 148
Minimizing Numerical Errors
Example
• To fix the problem, use an integer count to ensure that all the
numbers are added to sum.
• Here is the new loop:
TestSumFixWithWhileLoop.py
5.5 149
Minimizing Numerical Errors
Example
• Or, use a for loop as follows:
TestSumFixWithForLoop.py
5.5 150
5.6. Case Studies
▪ Program 7: Finding the GCD
▪ Program 8: Predicting The Future Tuition
151
Finding the GCD
Program 7
Write a program to ask the user to enter two positive integers.
You should then find the greatest common divisor (GCD) and
print the result to the user.
year += 1 # Year 1
tuition = tuition * 1.07
year += 1 # Year 2
tuition = tuition * 1.07
year += 1 # Year 3
tuition = tuition * 1.07
...
161
Keywords break and continue
• The break and continue keywords provide additional controls
to a loop.
• break keyword breaks out of a loop.
• continue keyword breaks out of an iteration.
• Benefits of using these keywords:
➢ Can simplify programming in some cases.
• Negatives of using these keywords:
➢ Overuse or improperly using them can cause problems and make
programs difficult to read and debug.
5.7 162
break Keyword
• You can use the keyword break in a loop to immediately
terminate a loop.
• Example:
LISTING 5.11 TestBreak.py
1 sum = 0 Run
2 number = 0
3
4 while number < 20:
5 number += 1
6 sum += number
7 if sum >= 100:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
The number is 14
The sum is 105
5.7 163
break Keyword
• Details: 1
LISTING 5.11 TestBreak.py
sum = 0
Run
◦ The program adds integers from 1 to 20 in 2 number = 0
3
this order to sum until sum is greater than 4 while number < 20:
or equal to 100. 5 number += 1
6 sum += number
◦ Without lines 7–8, this program would 7 if sum >= 100:
8 break
calculate the sum of the numbers from 1 to 9
20. 10 print("The number is", number)
11 print("The sum is", sum)
◦ But with lines 7–8, the loop terminates
when sum becomes greater than or equal to
100.
◦ Without lines 7–8, the output would be:
The number is 20
The sum is 210
5.7 164
Trace break Statement
sum → 0
1 sum = 0
2 number = 0
3
4 while number < 10: Initialize sum to 0
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 1 of 17 165
Trace break Statement
sum → 0 number → 0
1 sum = 0
2 number = 0
3
4 while number < 10: Initialize number to 0
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 2 of 17 166
Trace break Statement
sum → 0 number → 0
1 sum = 0
2 number = 0
3
4 while number < 10: 0 < 10 is True
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 3 of 17 167
Trace break Statement
sum → 0 number → 0 1
1 sum = 0
2 number = 0
3
4 while number < 10: Increment number by 1
number = 0 + 1
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 4 of 17 168
Trace break Statement
sum → 0 1 number → 1
1 sum = 0
2 number = 0
3
4 while number < 10: Add number to sum
sum = 0 + 1
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 5 of 17 169
Trace break Statement
sum → 1 number → 1
1 sum = 0
2 number = 0
3
4 while number < 10: 1 >= 5 is False
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 6 of 17 170
Trace break Statement
sum → 1 number → 1
1 sum = 0
2 number = 0
3
4 while number < 10: 1 < 10 is True
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 7 of 17 171
Trace break Statement
sum → 1 number → 1 2
1 sum = 0
2 number = 0
3
4 while number < 10: Increment number by 1
number = 1 + 1
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 8 of 17 172
Trace break Statement
sum → 1 3 number → 2
1 sum = 0
2 number = 0
3
4 while number < 10: Add number to sum
sum = 1 + 2
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 9 of 17 173
Trace break Statement
sum → 3 number → 2
1 sum = 0
2 number = 0
3
4 while number < 10: 3 >= 5 is False
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 10 of 17 174
Trace break Statement
sum → 3 number → 2
1 sum = 0
2 number = 0
3
4 while number < 10: 2 < 10 is True
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 11 of 17 175
Trace break Statement
sum → 3 number → 2 3
1 sum = 0
2 number = 0
3
4 while number < 10: Increment number by 1
number = 2 + 1
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 12 of 17 176
Trace break Statement
sum → 3 6 number → 3
1 sum = 0
2 number = 0
3
4 while number < 10: Add number to sum
sum = 3 + 3
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 13 of 17 177
Trace break Statement
sum → 6 number → 3
1 sum = 0
2 number = 0
3
4 while number < 10: 6 >= 5 is True
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 14 of 17 178
Trace break Statement
sum → 6 number → 3
1 sum = 0
2 number = 0
3
4 while number < 10: Exit the current loop
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
5.7 15 of 17 179
Trace break Statement
sum → 6 number → 3
1 sum = 0
2 number = 0
3
4 while number < 10: Print “The number is 3”
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
The number is 3
5.7 16 of 17 180
Trace break Statement
sum → 6 number → 3
1 sum = 0
2 number = 0
3
4 while number < 10: Print “The sum is 6”
5 number += 1
6 sum += number
7 if sum >= 5:
8 break
9
10 print("The number is", number)
11 print("The sum is", sum)
The number is 3
The sum is 6
5.7 17 of 17 181
continue Keyword
• You can use the continue keyword in a loop to end the current
iteration, and program control goes to the end of the loop
body.
• Example:
LISTING 5.12 TestContinue.py
1 sum = 0 Run
2 number = 0
3
4 while number < 20:
5 number += 1
6 if number == 10 or number == 11:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 182
continue Keyword
• Details: 1
LISTING 5.12 TestContinue.py
sum = 0
Run
◦ The program adds all the integers from 1 2 number = 0
3
to 20 except 10 and 11 to sum. 4 while number < 20:
5 number += 1
◦ The continue statement is executed 6 if number == 10 or number == 11:
when number becomes 10 or 11. 7 continue
8 sum += number
◦ It ends the current iteration so that the 9
10 print("The sum is", sum)
rest of the statement in the loop body is
not executed; therefore, number is not
added to sum when it is 10 or 11.
◦ Without lines 6 and 7, the output would
be as follows:
The sum is 210
1 sum = 0
2 number = 0
3
4 while number < 4:
Initialize sum to 0
5 number += 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 1 of 20 184
Trace continue Statement
sum → 0 number → 0
1 sum = 0
2 number = 0
3
4 while number < 4:
Initialize number to 0
5 number += 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 2 of 20 185
Trace continue Statement
sum → 0 number → 0
1 sum = 0
2 number = 0
3
4 while number < 4:
0 < 4 is True
5 number += 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 3 of 20 186
Trace continue Statement
sum → 0 number → 0 1
1 sum = 0
2 number = 0
3
4 while number < 4: Increment number by 1
5 number += 1 number = 0 + 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 4 of 20 187
Trace continue Statement
sum → 0 number → 1
1 sum = 0
2 number = 0
3
4 while number < 4: (1 == 1) or ( 1 == 3) is
5 number += 1 True
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 5 of 20 188
Trace continue Statement
sum → 0 number → 1
1 sum = 0
2 number = 0
3
4 while number < 4: End the current
5 number += 1 iteration
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 6 of 20 189
Trace continue Statement
sum → 0 number → 1
1 sum = 0
2 number = 0
3
4 while number < 4:
1 < 4 is True
5 number += 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 7 of 20 190
Trace continue Statement
sum → 0 number → 1 2
1 sum = 0
2 number = 0
3
4 while number < 4: Increment number by 1
5 number += 1 number = 1 + 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 8 of 20 191
Trace continue Statement
sum → 0 number → 2
1 sum = 0
2 number = 0
3
4 while number < 4: (2 == 1) or ( 2 == 3) is
5 number += 1 False
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 9 of 20 192
Trace continue Statement
sum → 0 2 number → 2
1 sum = 0
2 number = 0
3
4 while number < 4: Add number to sum
5 number += 1 sum = 0 + 2
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 10 of 20 193
Trace continue Statement
sum → 2 number → 2
1 sum = 0
2 number = 0
3
4 while number < 4:
2 < 4 is True
5 number += 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 11 of 20 194
Trace continue Statement
sum → 2 number → 2 3
1 sum = 0
2 number = 0
3
4 while number < 4: Increment number by 1
5 number += 1 number = 2 + 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 12 of 20 195
Trace continue Statement
sum → 2 number → 3
1 sum = 0
2 number = 0
3
4 while number < 4: (3 == 1) or (3 == 3) is
5 number += 1 True
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 13 of 20 196
Trace continue Statement
sum → 2 number → 3
1 sum = 0
2 number = 0
3
4 while number < 4: End the current
5 number += 1 iteration
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 14 of 20 197
Trace continue Statement
sum → 2 number → 3
1 sum = 0
2 number = 0
3
4 while number < 4:
3 < 4 is True
5 number += 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 15 of 20 198
Trace continue Statement
sum → 2 number → 3 4
1 sum = 0
2 number = 0
3
4 while number < 4: Increment number by 1
5 number += 1 number = 3 + 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 16 of 20 199
Trace continue Statement
sum → 2 number → 4
1 sum = 0
2 number = 0
3
4 while number < 4: (4 == 1) or ( 4 == 3) is
5 number += 1 False
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 17 of 20 200
Trace continue Statement
sum → 2 6 number → 4
1 sum = 0
2 number = 0
3
4 while number < 4: Add number to sum
5 number += 1 sum = 2 + 4
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 18 of 20 201
Trace continue Statement
sum → 6 number → 4
1 sum = 0
2 number = 0
3
4 while number < 4:
4 < 4 is False
5 number += 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
5.7 19 of 20 202
Trace continue Statement
sum → 6 number → 4
1 sum = 0
2 number = 0
3
4 while number < 4:
Print “The sum is 6”
5 number += 1
6 if number == 1 or number == 3:
7 continue
8 sum += number
9
10 print("The sum is", sum)
The sum is 6
5.7 20 of 20 203
When to Use break or continue?
• You can always write a program without using break or
continue in a loop.
• In general, it is appropriate to use break and continue if their
use simplifies coding and makes programs easy to read.
• Suppose you need to write a program to find the smallest
factor other than 1 for an integer n (assume n >= 2).
◦ You can write a simple code using the break statement as follows:
1 n = eval(input("Enter an integer >= 2: "))
2 factor = 2
3 while factor <= n:
4 if n % factor == 0:
5 break
6 factor += 1
7 print("The smallest factor other than 1 for", n, "is", factor)
5.7 204
Information
Factors of a Number
• The factors of a number are the numbers that divide evenly
into the number.
• For example: the factors of the number 12 are the numbers 1,
2, 3, 4, 6 and 12.
▪ 12 % 1 = 0 12 % 2 = 0 12 % 3 = 0
▪ 12 % 4 = 0 12 % 5 = 2 12 % 6 = 0
▪ 12 % 7 = 5 12 % 8 = 4 12 % 9 = 3
▪ 12 % 10 = 2 12 % 11 = 1 12 % 12 = 0
• Notice that the smallest factor is always 1 and the biggest
factor is always the number itself.
5.7 205
When to Use break or continue?
• You may rewrite the code without using break as follows:
1 n = eval(input("Enter an integer >= 2: ")) Run
2 found = False
3 factor = 2
4 while factor <= n and not found:
5 if n % factor == 0:
6 found = True
7 else:
8 factor += 1
9 print("The smallest factor other than 1 for", n, "is", factor)
5.7 206
Check Point
#17
What is the keyword break for? What is the keyword continue
for? Will the following program terminate? If so, give the output.
1 balance = 1000 1 balance = 1000
2 while True: 2 while True:
3 if balance < 9: 3 if balance < 9:
4 break 4 continue
5 balance = balance - 9 5 balance = balance - 9
6 print("Balance is", balance) 6 print("Balance is", balance)
(a) (b)
➢ Answer:
▪ The keyword break is used to exit the current loop.
▪ The keyword continue causes the rest of the loop body to be skipped for the
current iteration.
▪ The program in (a) will terminate. The output is Balance is 1.
▪ The while loop will not terminate in (b).
5.7 207
Check Point
#18
The for loop on the left is converted into the while loop on the
right. What is wrong? Correct it.
1 sum = 0
1 sum = 0 2 i = 0
2 for i in range(4): 3 while i < 4:
3 if i % 3 == 0: Converted 4 if i % 3 == 0:
4 continue 5 continue
Wrong Conversion
5 sum += i 6 sum += i
6 print(sum) 7 i += 1
(a) 8 print(sum)
(b) Wrong
➢ Answer:
▪ In (a), If the continue statement is executed inside the for loop, the rest of the
iteration is skipped, then the loop control variable (i) is being updated to the
next unused item in the sequence. This code (a) is correct.
▪ In (b), If the continue statement is executed inside the while loop, the rest of the
iteration is skipped, and the loop control variable (i) wouldn't get updated, so
the loop condition will be always True. This code (b) has an infinite loop.
5.7 208
Check Point
#18
The for loop on the left is converted into the while loop on the
right. What is wrong? Correct it.
5.7 209
Check Point
#19
After the break statement is executed in the following loop,
which statement is executed? Show the output.
1 for i in range(1, 4):
2 for j in range(1, 4): 1
3 if i * j > 2: 2
4 break 1
5 2
6 print(i * j) 2
7 3
8 print(i)
➢ Answer:
➢ The break keyword immediately ends the innermost loop, which contains the
break.
➢ So, print(i) is the next statement that will be executed.
5.7 210
Check Point
#20
After the continue statement is executed in the following loop,
which statement is executed? Show the output.
1 for i in range(1, 4):
2 for j in range(1, 4): 1
3 if i * j > 2: 2
4 continue 1
5 2
6 print(i * j) 2
7 3
8 print(i)
➢ Answer:
➢ The continue keyword ends only the current iteration.
➢ If j is not the last item in the sequence, j is getting updated to the next unused
item in the sequence, and if i * j > 2 is the next statement that will be executed.
➢ If j is the last item in the sequence, print(i) is the next statement that will be
executed.
5.7 211
Check Point
#21
Rewrite the following program without using break and continue
statements.
5.7 212
Check Point
#22
Rewrite the following program without using break and continue
statements.
5.7 213
5.8. Case Study: Displaying Prime
Numbers
▪ Program 9: Prime Number
▪ Coding with Loops
214
Prime Number
Program 9
Write a program to display the first 50 prime numbers in five
lines (so 10 numbers per line).
• Note: any integer greater than 1 is prime if it can only be divided by
1 or itself.
• Example:
▪ 2, 3, 5, and 7 are prime numbers
▪ 4, 6, 8, and 9 are not prime numbers
• So, we need now to filter the numbers and display only the
prime numbers.
• This will be the next step.
5.8 224
End
▪ Test Questions
▪ Programming Exercises
225
Test Questions
• Do the test questions for this chapter online at
https://liveexample-ppe.pearsoncmg.com/selftest/selftestpy?chapter=5
End 226
Programming Exercises
• Page 158 – 167:
◦ 5.1 - 5.16
◦ 5.18 - 5.22
◦ 5.23 – 5.41
◦ 5.43 – 5.46
• Lab #7
• Lab #8
End 227