Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
CHAPTER 5 LOOPS
1
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
MOTIVATIONS
Suppose that you need to print a string (e.g., "Programming
is fun!") a hundred times. It would be tedious to have to
write the following statement a hundred times:
print("Programming is fun!");
So, how do you solve this problem?
2
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
OPENING PROBLEM
Problem:
print("Programming
print("Programming
print("Programming
print("Programming
print("Programming
print("Programming
100
times
is
is
is
is
is
is
fun!");
fun!");
fun!");
fun!");
fun!");
fun!");
…
…
…
print("Programming is fun!");
print("Programming is fun!");
print("Programming is fun!");
3
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
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 obtain a large amount of input from a file by using input
redirection instead of typing from the keyboard (§5.2.6).
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).
To use a loop to control and simulate a random walk (§5.9).
4
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
INTRODUCING WHILE LOOPS
count = 0
while count < 100:
print("Programming is fun!")
count = count + 1
5
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
WHILE LOOP FLOW CHART
while loop-continuation-condition:
# Loop body
Statement(s)
count = 0
while count < 100:
print("Programming is fun!")
count = count + 1
count = 0
loopcontinuation
condition?
False
count < 100?
True
True
Statement(s)
(loop body)
(a)
False
print("Programming is fun!")
count = count + 1
(b)
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
6
animation
TRACE WHILE LOOP
Initialize count
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
7
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
animation
TRACE WHILE LOOP, CONT.
(count < 2) is true
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
8
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
animation
TRACE WHILE LOOP, CONT.
Print Welcome to Python
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
9
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
animation
TRACE WHILE LOOP, CONT.
Increase count by 1
count is 1 now
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
10
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
animation
TRACE WHILE LOOP, CONT.
(count < 2) is still true since count
is 1
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
11
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
animation
TRACE WHILE LOOP, CONT.
Print Welcome to Python
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
12
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
animation
TRACE WHILE LOOP, CONT.
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
Increase count by 1
count is 2 now
13
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
animation
TRACE WHILE LOOP, CONT.
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
(count < 2) is false since count is 2
now
14
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
animation
TRACE WHILE LOOP
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
The loop exits. Execute the next
statement after the loop.
15
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
PROBLEM: GUESSING NUMBERS
Write a program that randomly generates an integer between 0
and 100, inclusive. The program prompts the user to enter a
number continuously until the number matches the randomly
generated number. For each user input, the program tells the user
whether the input is too low or too high, so the user can choose
the next input intelligently. Here is a sample run:
GuestNumberOneTime
GuessNumber
16
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Run
PROBLEM: AN ADVANCED MATH
LEARNING TOOL
The Math subtraction learning tool program generates just one
question for each run. You can use a loop to generate questions
repeatedly. This example gives a program that generates five
questions and reports the number of the correct answers after a
student answers all five questions.
SubtractionQuizLoop
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
17
Run
ENDING A LOOP WITH A SENTINEL VALUE
Often the number of times a loop is executed is not predetermined.
You may use an input value to signify the end of the loop. Such a
value is known as a sentinel value.
Write a program that reads and calculates the sum of an unspecified
number of integers. The input 0 signifies the end of the input.
SentinelValue
18
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Run
C AUTION
Don’t use floating-point values for equality checking in a loop control. Since floatingpoint values are approximations for some values, using them could result in imprecise
counter values and inaccurate results. Consider the following code for computing 1 +
0.9 + 0.8 + ... + 0.1:
item = 1
sum = 0
while item != 0: # No guarantee item will be 0
sum += item
item -= 0.1
print(sum)
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. This loop seems OK on the surface, but it is actually an infinite loop.
InfiniteLoop
19
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Run
FOR LOOPS
i = initialValue # Initialize loop-control variable
while i < endValue:
# Loop body
...
i++ # Adjust loop-control variable
for i in range(initialValue, endValue):
# Loop body
20
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
RANGE(A, B)
>>> for v in range(4, 8):
...
print(v)
...
4
5
6
7
>>>
21
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
RANGE(B)
>>> for i in range(4):
...
print(i)
...
0
1
2
3
>>>
22
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
RANGE(A, B, STEP)
>>> for v in range(3, 9, 2):
...
print(v)
...
3
5
7
>>>
23
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
RANGE(A, B, STEP)
>>> for v in range(5, 1, -1):
...
print(v)
...
5
4
3
2
>>>
Note: The numbers in the range function must be integers.
24
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
NESTED LOOPS
Problem: Write a program that uses nested for
loops to print a multiplication table.
MultiplicationTable
25
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Run
NestedLoopTime
26
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Run
MINIMIZING NUMERIC AL ERRORS
Numeric errors involving floating-point numbers are
inevitable. This section discusses how to minimize such
errors through an example.
Here is an example that 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.
TestSum
27
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Run
After this loop, sum = 50.5
28
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
29
PROBLEM:
FINDING THE GREATEST COMMON
DIVISOR
Problem: Write a program that prompts the user to enter two positive
integers and finds their greatest common divisor.
Solution: Suppose you enter two integers 4 and 2, their greatest
common divisor is 2. Suppose you enter two integers 16 and 24, their
greatest common divisor is 8. So, how do you find the greatest
common divisor? Let the two input integers be n1 and n2. You know
number 1 is a common divisor, but it may not be the greatest commons
divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a
common divisor for n1 and n2, until k is greater than n1 or n2.
GreatestCommonDivisor
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
30
Run
It does not include n1 or n2 as a possible divisor
31
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
PROBLEM: PREDICTING THE FUTURE
TUITION
Problem: Suppose that the tuition for a university is $10,000 this year
and tuition increases 7% every year. In how many years will the
tuition be doubled?
FutureTuition
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
32
Run
USING
BREAK AND CONTINUE
Examples for using the break and continue
keywords:
TestBreak
TestContinue
33
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Run
BREAK
sum = 0
number = 0
Break out of
the loop
while number < 20:
number += 1
sum += number
if sum >= 100:
break
print("The number is ", number)
print("The sum is ", sum)
34
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
CONTINUE
sum = 0
number = 0
Jump to the
end of the
iteration
while (number < 20):
number += 1
if (number == 10 or number == 11):
continue
sum += number
print("The sum is ", sum)
35
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
37
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
GUESSING NUMBER PROBLEM REVISITED
Here is a program for guessing a number. You can rewrite it
using a break statement.
GuessNumberUsingBreak
37
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Run
PROBLEM: DISPLAYING PRIME NUMBERS
Problem: Write a program that displays the first 50 prime numbers in
five lines, each of which contains 10 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.
Solution: The problem can be broken into the following tasks:
• For number = 2, 3, 4, 5, 6, ..., test whether the number is prime.
• Count the prime numbers.
• Print each prime number, and print 10 numbers per line.
38
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Algorithm for the Problem
PrimeNumber
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
40
Run
TURTLE: RANDOM WALK
RandomWalk
40
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Run