Python Programming: An Introduction to Computer Science
Chapter 7 Decision Structures
Python Programming, 2/e 1
The University of Western Australia
Objectives
æ To understand the programming pattern simple decision and its implementation using a Python if statement.
æ To understand the programming pattern two-way decision and its implementation using a Python if-else statement.
æ To understand the programming pattern multi-way decision and its implementation using a Python if-elif-else statement.
æ To understand the idea of exception handling and be able to write simple exception handling code that catches standard Python run-time errors.
Python Programming, 2/e 2
The University of Western Australia
Objectives (cont.)
æ To understand the concepts of definite and indefinite loops as they are realized in the Python for and while statements.
æ To understand the programming patterns interactive loop and sentinel loop and their implementations using a Python while statement.
æ To understand the programming pattern end-of-file loop and ways of implementing such loops in Python.
æ To be able to design and implement solutions to problems involving loop patterns including nested loop structures.
Python Programming, 2/e 3
The University of Western Australia
Simple Decisions
æ So far, we’ve viewed programs as sequences of instructions that are followed one after the other.
æ While this is a fundamental programming concept, it is not sufficient in itself to solve every problem. We need to be able to alter the sequential flow of a program to suit a particular situation.
Python Programming, 2/e 4
The University of Western Australia
Simple Decisions
æ Control structures allow us to alter this sequential program flow. æ In this chapter, we’ll learn about decision structures, which are statements
that allow a program to execute different sequences of instructions for different cases, allowing the program to “choose” an appropriate course of action.
Python Programming, 2/e 5
The University of Western Australia
Example: Temperature Warnings
æ Let’s return to our Celsius to Fahrenheit temperature conversion program from Chapter 2.
# convert.py # A program to convert Celsius temps to Fahrenheit # by: Susan Computewell def main(): celsius = eval(input("What is the Celsius temperature? ")) fahrenheit = 9/5 * celsius + 32 print("The temperature is", fahrenheit, "degrees Fahrenheit.") main()
Python Programming, 2/e 6
The University of Western Australia
Example: Temperature Warnings
æ Let’s say we want to modify that program to print a warning when the weather is extreme.
æ Any temperature over 90 degrees Fahrenheit and lower than 30 degrees Fahrenheit will cause a hot and cold weather warning, respectively.
Python Programming, 2/e 7
The University of Western Australia
Example: Temperature Warnings
æ Input the temperature in degrees Celsius (call it celsius) æ Calculate fahrenheit as 9/5 celsius + 32 æ Output fahrenheit æ If fahrenheit > 90
print a heat warning æ If fahrenheit > 30
print a cold warning
Python Programming, 2/e 8
The University of Western Australia
Example: Temperature Warnings
æ This new algorithm has two decisions at the end. The indentation indicates that a step should be performed only if the condition listed in the previous line is true.
Python Programming, 2/e 9
The University of Western Australia
Example: Temperature Warnings
Python Programming, 2/e 10
The University of Western Australia
Example: Temperature Warnings
# convert2.py # A program to convert Celsius temps to Fahrenheit. # This version issues heat and cold warnings. def main(): celsius = eval(input("What is the Celsius temperature? ")) fahrenheit = 9 / 5 * celsius + 32 print("The temperature is", fahrenheit, "degrees fahrenheit.") if fahrenheit >= 90: print("It's really hot out there, be careful!") if fahrenheit <= 30: print("Brrrrr. Be sure to dress warmly") main()
Python Programming, 2/e 11
The University of Western Australia
Example: Temperature Warnings
æ The Python if statement is used to implement the decision. æ if <condition>:
<body>
æ The body is a sequence of one or more statements indented under the if heading.
Python Programming, 2/e 12
The University of Western Australia
Example: Temperature Warnings
æ The semantics of the if should be clear. • First, the condition in the heading is evaluated. • If the condition is true, the sequence of statements in
the body is executed, and then control passes to the next statement in the program.
• If the condition is false, the statements in the body are skipped, and control passes to the next statement in the program.
Python Programming, 2/e 13
The University of Western Australia
Example: Temperature Warnings
Python Programming, 2/e 14
The University of Western Australia
Example: Temperature Warnings
æ The body of the if either executes or not depending on the condition. In any case, control then passes to the next statement after the if.
æ This is a one-way or simple decision.
Python Programming, 2/e 15
The University of Western Australia
Forming Simple Conditions
æ What does a condition look like? æ At this point, let’s use simple comparisons. æ <expr> <relop> <expr> æ <relop> is short for relational operator
Python Programming, 2/e 16
The University of Western Australia
Forming Simple Conditions
Python Mathematics Meaning
< < Less than
<= ≤ Less than or equal to
== = Equal to
>= ≥ Greater than or equal to
> > Greater than
!= ≠ Not equal to
Python Programming, 2/e 17
The University of Western Australia
Forming Simple Conditions
æ Notice the use of == for equality. Since Python uses = to indicate assignment, a different symbol is required for the concept of equality.
æ A common mistake is using = in conditions!
Python Programming, 2/e 18
The University of Western Australia
Forming Simple Conditions
æ Conditions may compare either numbers or strings. æ When comparing strings, the ordering is lexigraphic, meaning that the
strings are sorted based on the underlying Unicode. Because of this, all upper-case letters come before lower-case letters. (“Bbbb” comes before “aaaa”)
Python Programming, 2/e 19
The University of Western Australia
Forming Simple Conditions
æ Conditions are based on Boolean expressions, named for the English mathematician George Boole.
æ When a Boolean expression is evaluated, it produces either a value of true (meaning the condition holds), or it produces false (it does not hold).
æ Some computer languages use 1 and 0 to represent “true” and “false”.
Python Programming, 2/e 20
The University of Western Australia
Forming Simple Conditions
æ Boolean conditions are of type bool and the Boolean values of true and false are represented by the literals True and False.
>>> 3 < 4 True >>> 3 * 4 < 3 + 4 False >>> "hello" == "hello" True >>> "Hello" < "hello" True
Python Programming, 2/e 21
The University of Western Australia
Two-Way Decisions
æ Consider the quadratic program as we left it. # quadratic.py # A program that computes the real roots of a quadratic equation. # Note: This program crashes if the equation has no real roots. import math def main(): print("This program finds the real solutions to a quadratic") a, b, c = eval(input("\nPlease enter the coefficients (a, b, c): ")) discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print("\nThe solutions are:", root1, root2) main()
Python Programming, 2/e 22
The University of Western Australia
Two-Way Decisions
æ As per the comment, when b2-4ac < 0, the program crashes.
This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1,1,2 Traceback (most recent call last): File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 120\Textbook\code
\chapter3\quadratic.py", line 21, in -toplevel- main() File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS 120\Textbook\code
\chapter3\quadratic.py", line 14, in main discRoot = math.sqrt(b * b - 4 * a * c) ValueError: math domain error
Python Programming, 2/e 23
The University of Western Australia
Two-Way Decisions
æ We can check for this situation. Here’s our first attempt. # quadratic2.py # A program that computes the real roots of a quadratic equation. # Bad version using a simple if to avoid program crash import math def main(): print("This program finds the real solutions to a quadratic\n") a, b, c = eval(input("Please enter the coefficients (a, b, c): ")) discrim = b * b - 4 * a * c if discrim >= 0: discRoot = math.sqrt(discrim) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print("\nThe solutions are:", root1, root2)
Python Programming, 2/e 24
The University of Western Australia
Two-Way Decisions
æ We first calculate the discriminant (b2-4ac) and then check to make sure it’s nonnegative. If it is, the program proceeds and we calculate the roots.
æ Look carefully at the program. What’s wrong with it? Hint: What happens when there are no real roots?
Python Programming, 2/e 25
The University of Western Australia
Two-Way Decisions
æ This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1,1,1 >>>
æ This is almost worse than the version that crashes, because we don’t know what went wrong!
Python Programming, 2/e 26
The University of Western Australia
Two-Way Decisions
æ We could add another if to the end: if discrim < 0: print("The equation has no real roots!" )
æ This works, but feels wrong. We have two decisions, with mutually exclusive outcomes (if discrim >= 0 then discrim < 0 must be false, and vice versa).
Python Programming, 2/e 27
The University of Western Australia
Two-Way Decisions
Python Programming, 2/e 28
The University of Western Australia
Two-Way Decisions
æ In Python, a two-way decision can be implemented by attaching an else clause onto an if clause.
æ This is called an if-else statement: if <condition>: <statements> else: <statements>
Python Programming, 2/e 29
The University of Western Australia
Two-Way Decisions
æ When Python first encounters this structure, it first evaluates the condition. If the condition is true, the statements under the if are executed.
æ If the condition is false, the statements under the else are executed.
æ In either case, the statements following the if-else are executed after either set of statements are executed.
Python Programming, 2/e 30
The University of Western Australia
Two-Way Decisions
# quadratic3.py # A program that computes the real roots of a quadratic equation. # Illustrates use of a two-way decision import math def main(): print "This program finds the real solutions to a quadratic\n" a, b, c = eval(input("Please enter the coefficients (a, b, c): ")) discrim = b * b - 4 * a * c if discrim < 0: print("\nThe equation has no real roots!") else: discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print ("\nThe solutions are:", root1, root2 ) main()
Python Programming, 2/e 31
The University of Western Australia
Two-Way Decisions
>>> This program finds the real solutions to a quadratic
Please enter the coefficients (a, b, c): 1,1,2
The equation has no real roots!
>>>
This program finds the real solutions to a quadratic
Please enter the coefficients (a, b, c): 2, 5, 2
The solutions are: -0.5 -2.0
Python Programming, 2/e 32
The University of Western Australia
Multi-Way Decisions
æ The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic
Please enter the coefficients (a, b, c): 1,2,1 The solutions are: -1.0 -1.0
Python Programming, 2/e 33
The University of Western Australia
Multi-Way Decisions
æ While correct, this method might be confusing for some people. It looks like it has mistakenly printed the same number twice!
æ Double roots occur when the discriminant is exactly 0, and then the roots are –b/2a.
æ It looks like we need a three-way decision!
Python Programming, 2/e 34
The University of Western Australia
Multi-Way Decisions
æ Check the value of discrim when < 0: handle the case of no roots when = 0: handle the case of a double root when > 0: handle the case of two distinct
roots æ We can do this with two if-else statements, one inside the other. æ Putting one compound statement inside of another is called nesting.
Python Programming, 2/e 35
The University of Western Australia
Multi-Way Decisions
if discrim < 0:
print("Equation has no real roots") else:
if discrim == 0:
root = -b / (2 * a)
print("There is a double root at", root)
else: # Do stuff for two roots
Python Programming, 2/e 36
The University of Western Australia
Multi-Way Decisions
Python Programming, 2/e 37
The University of Western Australia
Multi-Way Decisions
æ Imagine if we needed to make a five-way decision using nesting. The if-else statements would be nested four levels deep!
æ There is a construct in Python that achieves this, combining an else followed immediately by an if into a single elif.
Python Programming, 2/e 38
The University of Western Australia
Multi-Way Decisions
æ if <condition1>: <case1 statements> elif <condition2>: <case2 statements> elif <condition3>: <case3 statements> … else: <default statements>
Python Programming, 2/e 39
The University of Western Australia
Multi-Way Decisions
æ This form sets of any number of mutually exclusive code blocks.
æ Python evaluates each condition in turn looking for the first one that is true. If a true condition is found, the statements indented under that condition are executed, and control passes to the next statement after the entire if-elif-else.
æ If none are true, the statements under else are performed.
Python Programming, 2/e 40
The University of Western Australia
Multi-Way Decisions
æ The else is optional. If there is no else, it’s possible no indented block would be executed.
Python Programming, 2/e 41
The University of Western Australia
Multi-Way Decisions
# quadratic4.py # Illustrates use of a multi-way decision import math def main(): print("This program finds the real solutions to a quadratic\n") a, b, c = eval(input("Please enter the coefficients (a, b, c): ")) discrim = b * b - 4 * a * c if discrim < 0: print("\nThe equation has no real roots!") elif discrim == 0: root = -b / (2 * a) print("\nThere is a double root at", root) else: discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print("\nThe solutions are:", root1, root2 )
Python Programming, 2/e 42
The University of Western Australia
For Loops: A Quick Review
æ The for statement allows us to iterate through a sequence of values. æ for <var> in <sequence>:
<body> æ The loop index variable var takes on each successive value in the
sequence, and the statements in the body of the loop are executed once for each value.
Python Programming, 2/e 43
The University of Western Australia
For Loops: A Quick Review
æ Suppose we want to write a program that can compute the average of a series of numbers entered by the user.
æ To make the program general, it should work with any size set of numbers.
æ We don’t need to keep track of each number entered, we only need know the running sum and how many numbers have been added.
Python Programming, 2/e 44
The University of Western Australia
For Loops: A Quick Review
æ We’ve run into some of these things before! • A series of numbers could be handled by some sort of loop. If there are
n numbers, the loop should execute n times. • We need a running sum. This will use an accumulator.
Python Programming, 2/e 45
The University of Western Australia
For Loops: A Quick Review
æ Input the count of the numbers, n æ Initialize sum to 0 æ Loop n times
• Input a number, x • Add x to sum
æ Output average as sum/n
Python Programming, 2/e 46
The University of Western Australia
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!
Python Programming, 2/e 47
The University of Western Australia
For Loops: A Quick Review
How many numbers do you have? 5 Enter a number >> 32
Enter a number >> 45
Enter a number >> 34
Enter a number >> 76
Enter a number >> 45
The average of the numbers is 46.4
Python Programming, 2/e 48
The University of Western Australia
Indefinite Loops
æ That last program got the job done, but you need to know ahead of time how many numbers you’ll be dealing with.
æ What we need is a way for the computer to take care of counting how many numbers there are.
æ The for loop is a definite loop, meaning that the number of iterations is determined when the loop starts.
Python Programming, 2/e 49
The University of Western Australia
Indefinite Loops
æ We can’t use a definite loop unless we know the number of iterations ahead of time. We can’t know how many iterations we need until all the numbers have been entered.
æ We need another tool! æ The indefinite or conditional loop keeps iterating until certain conditions are
met.
Python Programming, 2/e 50
The University of Western Australia
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.
Python Programming, 2/e 51
The University of Western Australia
Indefinite Loops
æ The condition is tested at the top of the loop. This is known as a pre-test loop. If the condition is initially false, the loop body will not execute at all.
Python Programming, 2/e 52
The University of Western Australia
Indefinite Loop
æ Here’s an example of a while loop that counts from 0 to 10: i = 0 while i <= 10: print(i) i = i + 1
æ The code has the same output as this for loop: for i in range(11): print(i)
Python Programming, 2/e 53
The University of Western Australia
Indefinite Loop
æ The while loop requires us to manage the loop variable i by initializing it to 0 before the loop and incrementing it at the bottom of the body.
æ In the for loop this is handled automatically.
Python Programming, 2/e 54
The University of Western Australia
Indefinite Loop
æ The while statement is simple, but yet powerful and dangerous – they are a common source of program errors.
æ i = 0 while i <= 10: print(i)
æ What happens with this code?
Python Programming, 2/e 55
The University of Western Australia
Indefinite Loop
æ When Python gets to this loop, i is equal to 0, which is less than 10, so the body of the loop is executed, printing 0. Now control returns to the condition, and since i is still 0, the loop repeats, etc.
æ This is an example of an infinite loop.
Python Programming, 2/e 56
The University of Western Australia
Indefinite Loop
æ What should you do if you’re caught in an infinite loop? • First, try pressing control-c • If that doesn’t work, try control-alt-delete • If that doesn’t work, push the reset button!
Python Programming, 2/e 57
The University of Western Australia
Interactive Loops
æ One good use of the indefinite loop is to write interactive loops. Interactive loops allow a user to repeat certain portions of a program on demand.
æ Remember how we said we needed a way for the computer to keep track of how many numbers had been entered? Let’s use another accumulator, called count.
Python Programming, 2/e 58
The University of Western Australia
Interactive Loops
æ At each iteration of the loop, ask the user if there is more data to process. We need to preset it to “yes” to go through the loop the first time.
æ set moredata to “yes” while moredata is “yes” get the next data item process the item ask user if there is moredata
Python Programming, 2/e 59
The University of Western Australia
Interactive Loops
æ Combining the interactive loop pattern with accumulators for sum and count:
æ initialize sum to 0.0 initialize count to 0 set moredata to “yes” while moredata is “yes” input a number, x add x to sum add 1 to count ask user if there is moredata output sum/count
Python Programming, 2/e 60
The University of Western Australia
Interactive Loops
# average2.py # A program to average a set of numbers # Illustrates interactive loop with two accumulators def main(): moredata = "yes" sum = 0.0 count = 0 while moredata[0] == 'y': x = eval(input("Enter a number >> ")) sum = sum + x count = count + 1 moredata = input("Do you have more numbers (yes or no)? ") print("\nThe average of the numbers is", sum / count)
æ Using string indexing (moredata[0]) allows us to accept “y”, “yes”, “yeah” to continue the loop
Python Programming, 2/e 61
The University of Western Australia
Interactive Loops
Enter a number >> 32 Do you have more numbers (yes or no)? y Enter a number >> 45 Do you have more numbers (yes or no)? yes Enter a number >> 34 Do you have more numbers (yes or no)? yup Enter a number >> 76 Do you have more numbers (yes or no)? y Enter a number >> 45 Do you have more numbers (yes or no)? nah The average of the numbers is 46.4
Python Programming, 2/e 62
The University of Western Australia
Sentinel Loops
æ A sentinel loop continues to process data until reaching a special value that signals the end.
æ This special value is called the sentinel. æ The sentinel must be distinguishable from the data since it is not processed
as part of the data.
Python Programming, 2/e 63
The University of Western Australia
Sentinel Loops
æ get the first data item while item is not the sentinel process the item get the next data item
æ The first item is retrieved before the loop starts. This is sometimes called the priming read, since it gets the process started.
æ If the first item is the sentinel, the loop terminates and no data is processed.
æ Otherwise, the item is processed and the next one is read.
Python Programming, 2/e 64
The University of Western Australia
Sentinel Loops
æ In our averaging example, assume we are averaging test scores. æ We can assume that there will be no score below 0, so a negative number
will be the sentinel.
Python Programming, 2/e 65
The University of Western Australia
Sentinel Loops
# average3.py # A program to average a set of numbers
# Illustrates sentinel loop using negative input as sentinel
def main():
sum = 0.0
count = 0
x = eval(input("Enter a number (negative to quit) >> "))
while x >= 0:
sum = sum + x
count = count + 1
x = eval(input("Enter a number (negative to quit) >> "))
print("\nThe average of the numbers is", sum / count)
Python Programming, 2/e 66
The University of Western Australia
Sentinel Loops
Enter a number (negative to quit) >> 32 Enter a number (negative to quit) >> 45
Enter a number (negative to quit) >> 34 Enter a number (negative to quit) >> 76
Enter a number (negative to quit) >> 45
Enter a number (negative to quit) >> -1
The average of the numbers is 46.4
Python Programming, 2/e 67
The University of Western Australia
Sentinel Loops
æ This version provides the ease of use of the interactive loop without the hassle of typing ‘y’ all the time.
æ There’s still a shortcoming – using this method we can’t average a set of positive and negative numbers.
æ If we do this, our sentinel can no longer be a number.
Python Programming, 2/e 68
The University of Western Australia
Sentinel Loops
æ We could input all the information as strings. æ Valid input would be converted into numeric form. Use a character-based
sentinel. æ We could use the empty string (“”)!
Python Programming, 2/e 69
The University of Western Australia
Sentinel Loops
initialize sum to 0.0
initialize count to 0 input data item as a string, xStr
while xStr is not empty
convert xStr to a number, x
add x to sum
add 1 to count input next data item as a string, xStr
Output sum / count
Python Programming, 2/e 70
The University of Western Australia
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)
sum = sum + x
count = count + 1
xStr = input("Enter a number (<Enter> to quit) >> ")
print("\nThe average of the numbers is", sum / count)
Python Programming, 2/e 71
The University of Western Australia
Sentinel Loops
Enter a number (<Enter> to quit) >> 34 Enter a number (<Enter> to quit) >> 23
Enter a number (<Enter> to quit) >> 0
Enter a number (<Enter> to quit) >> -25
Enter a number (<Enter> to quit) >> -34.4
Enter a number (<Enter> to quit) >> 22.7
Enter a number (<Enter> to quit) >>
The average of the numbers is 3.38333333333
Python Programming, 2/e 72
The University of Western Australia
File Loops
æ The biggest disadvantage of our program at this point is that they are interactive.
æ What happens if you make a typo on number 43 out of 50? æ A better solution for large data sets is to read the data from a file.
Python Programming, 2/e 73
The University of Western Australia
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)
Python Programming, 2/e 74
The University of Western Australia
File Loops
æ Many languages don’t have a mechanism for looping through a file like this. Rather, they use a sentinel!
æ We could use readline in a loop to get the next line of the file. æ At the end of the file, readline returns an empty string, “”
Python Programming, 2/e 75
The University of Western Australia
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” != “”
Python Programming, 2/e 76
The University of Western Australia
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)
Python Programming, 2/e 77
The University of Western Australia
Nested Loops
æ In the last chapter we saw how we could nest if statements. We can also nest loops.
æ Suppose we change our specification to allow any number of numbers on a line in the file (separated by commas), rather than one per line.
Python Programming, 2/e 78
The University of Western Australia
Nested Loops
æ At the top level, we will use a file-processing loop that computes a running sum and count.
sum = 0.0
count = 0
line = infile.readline() while line != "":
#update sum and count for values in line
line = infile.readline()
print("\nThe average of the numbers is", sum/count)
Python Programming, 2/e 79
The University of Western Australia
Nested Loops
æ In the next level in we need to update the sum and count in the body of the loop.
æ Since each line of the file contains one or more numbers separated by commas, we can split the string into substrings, each of which represents a number.
æ Then we need to loop through the substrings, convert each to a number, and add it to sum.
æ We also need to update count.
Python Programming, 2/e 80
The University of Western Australia
Nested Loops
æ for xStr in line.split(","): sum = sum + eval(xStr) count = count + 1
æ Notice that this for statement uses line, which is also the loop control variable for the outer loop.
Python Programming, 2/e 81
The University of Western Australia
Nested Loops
# average7.py # Computes the average of numbers listed in a file. # Works with multiple numbers on a line. import string def main(): fileName = input("What file are the numbers in? ") infile = open(fileName,'r') sum = 0.0 count = 0 line = infile.readline() while line != "": for xStr in line.split(","): sum = sum + eval(xStr) count = count + 1 line = infile.readline() print("\nThe average of the numbers is", sum / count)
Python Programming, 2/e 82
The University of Western Australia
Nested Loops
æ The loop that processes the numbers in each line is indented inside of the file processing loop.
æ The outer while loop iterates once for each line of the file.
æ For each iteration of the outer loop, the inner for loop iterates as many times as there are numbers on the line.
æ When the inner loop finishes, the next line of the file is read, and this process begins again.
Python Programming, 2/e 83
The University of Western Australia
Nested Loops
æ Designing nested loops – • Design the outer loop without worrying about what goes inside • Design what goes inside, ignoring the outer loop. • Put the pieces together, preserving the nesting.
Python Programming, 2/e 84