Lecture 5 Loop Structures
Lecture 5 Loop Structures
Lecture 5 Loop Structures
and Booleans
1
Objectives
2
Objectives
3
Objectives
4
For Loops: A Quick Review
5
For Loops: A Quick Review
6
For Loops iteration
7
For Loops: A Quick Review
8
For Loops: A Quick Review
9
For Loops: A Quick Review
# average1.py
# A program to average a set of numbers
# Illustrates counted loop with accumulator
def main():
n = eval(input("How many numbers do you have? "))
sum = 0.0
for i in range(n):
x = eval(input("Enter a number >> "))
sum = sum + x
print("\nThe average of the numbers is", sum / n)
Note that sum is initialized to 0.0 so that sum/n returns a float!
10
For Loops: A Quick Review
11
Example Program: Future
Value
Analysis
Money deposited in a bank account
earns interest.
How much will the account be worth
10 years from now?
Inputs: principal, interest rate
Output: value of the investment in 10
years
12
Example Program: Future
Value
Specification
User enters the initial amount to
invest, the principal
User enters an annual percentage rate,
the interest
The specifications can be represented
like this …
13
Example Program: Future
Value
Program Future Value
Inputs
principal The amount of money being invested, in
dollars
apr The annual percentage rate expressed as a
decimal number.
Output The value of the investment 10 years in the
future
Relationship Value after one year is given by
principal * (1 + apr). This needs to be done 10 times.
14
Example Program: Future
Value
Design
Display an introduction
Get the amount of the principal
(principal)
Get the annual percentage rate (apr)
Repeat 10 times:
principal = principal * (1 + apr)
Output the value of principal
15
Example Program: Future
Value
Implementation
Print an introduction
print ("This program calculates the future")
print ("value of a 10-year investment.")
Repeat 10 times:
for i in range(10):
def main():
print("This program calculates the future value of a 10-year
investment.")
for i in range(10):
principal = principal * (1 + apr)
main() 18
Example Program: Future
Value
>>> main()
This program calculates the future value of a 10-year
investment.
Enter the initial principal: 100
Enter the annual interest rate: .03
The value in 10 years is: 134.391637934
>>> main()
This program calculates the future value of a 10-year
investment.
Enter the initial principal: 100
Enter the annual interest rate: .10
The value in 10 years is: 259.37424601
19
Indefinite Loops
20
Indefinite Loops
21
Indefinite Loops
while <condition>:
<body>
condition is a Boolean expression,
just like in if statements. The body is
a sequence of one or more
statements.
Semantically, the body of the loop
executes repeatedly as long as the
condition remains true. When the
condition is false, the loop terminates.
22
Indefinite Loops
24
Indefinite Loop
25
Indefinite Loop
26
Indefinite Loop
27
Indefinite Loop
28
Exercise
29
Indefinite loop
30
Interactive Loops
33
Interactive Loops
# average2.py
# A program to average a set of numbers
# Illustrates interactive loop with two accumulators
def main():
moredata = "yes"
total = 0.0
count = 0
while moredata[0] == 'y':
x = eval(input("Enter a number >> "))
total = total + x
count = count + 1
moredata = input("Do you have more numbers (yes or no)? ")
print("\nThe average of the numbers is", total / count)
35
Exercise
36
Indefinite loop
37
Sentinel Loops
40
Sentinel Loops
# average3.py
# A program to average a set of numbers
# Illustrates sentinel loop using negative input as sentinel
def main():
total = 0.0
count = 0
x = eval(input("Enter a number (negative to quit) >> "))
while x >= 0:
total = total + x
count = count + 1
x = eval(input("Enter a number (negative to quit) >> "))
print("\nThe average of the numbers is", total / count)
41
Sentinel Loops
42
Sentinel Loops
43
Sentinel Loops
44
Sentinel Loops
# average4.py
# A program to average a set of numbers
# Illustrates sentinel loop using empty string as sentinel
def main():
sum = 0.0
count = 0
xStr = input("Enter a number (<Enter> to quit) >> ")
while xStr != "":
x = eval(xStr)
total = total + x
count = count + 1
xStr = input("Enter a number (<Enter> to quit) >> ")
print("\nThe average of the numbers is", total / count)
46
Sentinel Loops
47
File Loops
48
File Loops
# average5.py
# Computes the average of numbers listed in a
file.
def main():
fileName = input("What file are the numbers
in? ")
infile = open(fileName,'r')
sum = 0.0
count = 0
for line in infile.readlines():
sum = sum + eval(line)
count = count + 1
print("\nThe average of the numbers is", sum /
count)
49
File Loops
50
File Loops
line = infile.readline()
while line != ""
#process line
line = infile.readline()
Does this code correctly handle the case where there’s a
blank line in the file?
Yes. An empty line actually ends with the newline
character, and readline includes the newline. “\n” !=
“”
51
File Loops
# average6.py
# Computes the average of numbers listed in a file.
def main():
fileName = input("What file are the numbers in? ")
infile = open(fileName,'r')
sum = 0.0
count = 0
line = infile.readline()
while line != "":
sum = sum + eval(line)
count = count + 1
line = infile.readline()
print("\nThe average of the numbers is", sum / count)
52
Nested Loops
53
Nested loop – Clock example
54
Nested loop
56
Computing with Booleans
57
Boolean Operators
58
Boolean Operators
F F F
Boolean Expressions
60
Boolean Expressions
P Q P or Q
T T T
T F T
F T T
F F F
61
Boolean Operators
P not P
T F
F T
62
Boolean Operators
63
Boolean Operators
65
Post-Test Loop
66
Post-Test Loop
repeat
get a number from the user
until number is >= 0
67
Post-Test Loop
68
Post-Test Loop
69
Boolean Expressions
as Decisions
Boolean expressions can be used as
control structures themselves.
Suppose you’re writing a program that
keeps going as long as the user enters a
response that starts with ‘y’ (like our
interactive loop).
One way you could do it:
while response[0] == "y" or
response[0] == "Y":
70
Boolean Expressions
as Decisions
>>> bool(0)
False
>>> bool(1)
True
>>> bool(32)
True
>>> bool("Hello")
True
>>> bool("")
False
>>> bool([1,2,3])
True
>>> bool([])
False
71
Boolean Expressions
as Decisions
An empty sequence is interpreted as
False while any non-empty sequence is
taken to mean True.
The Boolean operators have operational
definitions that make them useful for
other purposes.
72
Boolean Expressions
as Decisions
Sometimes we write programs that
prompt for information but offer a
default value obtained by simply pressing
<Enter>
Since the string used by ans can be
treated as a Boolean, the code can be
further simplified.
73
Boolean Expressions
as Decisions
ans = input("What flavor do you
want [vanilla]: ")
if ans:
flavor = ans
else:
flavor = "vanilla"
If the user just hits <Enter>, ans will be
an empty string, which Python interprets
as false.
74