Python Programming: An Introduction to Computer Science

Similar documents
Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

File processing and decision structures

Introduction to Computer Programming for Non-Majors

Lecture. Loops && Booleans. Richard E Sarkis CSC 161: The Art of Programming

Loop structures and booleans

Python Programming: An Introduction To Computer Science

" # # if $ " %&% # ifelse $ " #&% # ifelif-else $ +bool ##%# # #.* $ ## # .# *#%$ % ## % .#*#%*

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Multi-Way Decisions. The newest program is great, but it still has some quirks! This program finds the real solutions to a quadratic

Decision Structures CSC1310. Python Programming, 2/e 1

Python Programming: An Introduction to Computer Science

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

CITS 1401 Problem Solving & Programming

Python Programming: An Introduction to Computer Science

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

Chapter 2 Writing Simple Programs

Python Programming: An Introduction to Computer Science

CITS 4406 Problem Solving & Programming

Python Programming: An Introduction to Computer Science

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

SI Networked Computing: Storage, Communication, and Processing, Winter 2009

CMSC201 Computer Science I for Majors

Writing Python Programs, Numerical Data Types

Comp 151. Control structures.

Control structure: Repetition - Part 2

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

LOOPS. Repetition using the while statement

Python for Informatics

CS 115 Lecture 4. More Python; testing software. Neil Moore

Comp 151. Control structures.

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Condition Controlled Loops. Introduction to Programming - Python

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

Text Input and Conditionals

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Test #2 October 8, 2015

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

If Statements, For Loops, Functions

C++ Programming: From Problem Analysis to Program Design, Third Edition

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Conditional Expressions and Decision Statements

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Control structure: Selections

A453 Task 1: Analysis: Problem: Solution:

Last Time. integer/float/string. import math math.sqrt() math.pi. Python Programming, 2/e 2

Intro. Speed V Growth

CS 115 Lecture 8. Selection: the if statement. Neil Moore

Control and Environments Fall 2017 Discussion 1: August 30, 2017 Solutions. 1 Control. If statements. Boolean Operators

Decision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2>

(Python) Chapter 3: Repetition

CS112 Lecture: Repetition Statements

MITOCW watch?v=0jljzrnhwoi

SSEA Computer Science: Track A. Dr. Cynthia Lee Lecturer in Computer Science Stanford

REPETITION CONTROL STRUCTURE LOGO

Control Structures 1 / 17

Principles of Computer Science I

Name Section: M/W T/TH Number Definition Matching (6 Points)

Computing with Numbers

CS112 Lecture: Loops

Worlframalpha.com Facebook Report

Chapter 4: Making Decisions

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Chapter 4: Making Decisions

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Intro. Scheme Basics. scm> 5 5. scm>

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Name Section: M/W T/TH Number Definition Matching (8 Points)

5. Control Statements

Flow Charts. Visual Depiction of Logic Flow

Lecture 7 Tao Wang 1

Python Programming: An Introduction to Computer Science

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

SECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Lists, loops and decisions

CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Ch.2: Loops and lists

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

Python Evaluation Rules

Transcription:

Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures Python Programming, 2/e 1

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. 2

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. 3

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. 4

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. 5

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() 6

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. 7

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 8

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. 9

Example: Temperature Warnings 10

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() 11

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. 12

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. 13

Example: Temperature Warnings 14

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. 15

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 16

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 17

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! 18

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 ) 19

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. 20

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 21

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") main() 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) 22

Two-Way Decisions æ As per the comment, when b 2-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 -toplevelmain() 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 23

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) 24

Two-Way Decisions æ We first calculate the discriminant (b 2-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? 25

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! 26

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). 27

Two-Way Decisions 28

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> 29

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 ifelse are executed after either set of statements are executed. 30

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" main() 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 ) 31

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 32

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 33

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! 34

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. 35

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 36

Multi-Way Decisions 37

Multi-Way Decisions æ Imagine if we needed to make a five-way decision using nesting. The ifelse 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. 38

Multi-Way Decisions æ if <condition1>: <case1 statements> elif <condition2>: <case2 statements> elif <condition3>: <case3 statements> else: <default statements> 39

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-elifelse. æ If none are true, the statements under else are performed. 40

Multi-Way Decisions æ The else is optional. If there is no else, it s possible no indented block would be executed. 41

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 ) 42

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. 43

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. 44

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. 45

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 46

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! 47

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 48

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. 49

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. 50

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. 51

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. 52

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) 53

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. 54

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? 55

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. 56

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! 57

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. 58

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 59

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 60

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 61

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 62

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. 63

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. 64

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. 65

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) 66

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 67

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. 68

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 ( )! 69

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 70

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) 71

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 72

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. 73

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) 74

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, 75

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!= 76

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) 77

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. 78

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) 79

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. 80

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. 81

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) 82

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. 83

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. 84