# Python Programming: An Introduction to Computer Programming: An Introduction to Computer Science Chapter…

Post on 29-Jun-2018

212 views

Category:

## Documents

0 download

TRANSCRIPT

• 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, weve 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, well 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

Lets 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

Lets 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

• The University of Western Australia

Example: Temperature Warnings

The Python if statement is used to implement the decision. if :

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, lets use simple comparisons. is short for relational operator

Python Programming, 2/e 16

• The University of Western Australia

Forming Simple Conditions

Python Mathematics Meaning

< < Less than

= 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. Heres 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 its nonnegative. If it is, the program proceeds and we calculate the roots.

Look carefully at the program. Whats 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 dont 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 : else:

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 : elif : elif : else:

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, its 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 in :

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

Weve 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 youll 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 cant use a definite loop unless we know the number of iterations ahead of time. We cant 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 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

Heres an example of a while loop that counts from 0 to 10: i = 0 while i

• 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

• 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 youre caught in an infinite loop? First, try pressing control-c If that doesnt work, try control-alt-delete If that doesnt 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? Lets 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 == '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) 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.

Theres still a shortcoming using this method we cant 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 ( to quit) >> ")

while xStr != "":

x = eval(xStr)

sum = sum + x

count = count + 1

xStr = input("Enter a number ( 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 ( to quit) >> 34 Enter a number ( to quit) >> 23

Enter a number ( to quit) >> 0

Enter a number ( to quit) >> -25

Enter a number ( to quit) >> -34.4

Enter a number ( to quit) >> 22.7

Enter a number ( 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 dont 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 theres 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