Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To...

91
Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e 1

Transcript of Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To...

Page 1: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

Python Programming: An Introduction To Computer Science

Chapter 8 Booleans and Control Structures

Python Programming, 2/e 1

Page 2: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Objectives

æ  To understand the concept of Boolean expressions and the bool data type. æ  To be able to read, write, and implement algorithms that employ decision

structures, including those that employ sequences of decisions and nested decision structures.

æ  To understand the basic ideas of Boolean algebra and be able to analyze and write Boolean expressions involving Boolean operators.

Python Programming, 2/e 2

Page 3: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Computing with Booleans

æ  if and while both use Boolean expressions. æ  Boolean expressions evaluate to True or False. æ  So far we’ve used Boolean expressions to compare two values, e.g.

(while x >= 0)

Python Programming, 2/e 3

Page 4: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ  Sometimes our simple expressions do not seem expressive enough. æ  Suppose you need to determine whether two points are in the same

position – their x coordinates are equal and their y coordinates are equal.

Python Programming, 2/e 4

Page 5: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ  if p1.getX() == p2.getX(): if p1.getY() == p2.getY(): # points are the same else: # points are different else: # points are different

æ Clearly, this is an awkward way to evaluate multiple Boolean expressions!

æ Let’s check out the three Boolean operators and, or, and not.

Python Programming, 2/e 5

Page 6: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ  The Boolean operators and and or are used to combine two Boolean expressions and produce a Boolean result.

æ  <expr> and <expr> æ  <expr> or <expr>

Python Programming, 2/e 6

Page 7: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ The and of two expressions is true exactly when both of the expressions are true.

æ We can represent this in a truth table.

Python Programming, 2/e 7

P Q P and Q T T T T F F F T F F F F

Page 8: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions

æ  In the truth table, P and Q represent smaller Boolean expressions. æ  Since each expression has two possible values, there are four possible

combinations of values. æ  The last column gives the value of P and Q.

Python Programming, 2/e 8

Page 9: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions

æ The or of two expressions is true when either expression is true.

P Q P or Q T T T T F T

F T T F F F

Python Programming, 2/e 9

Page 10: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions

æ  The only time or is false is when both expressions are false. æ  Also, note that or is true when both expressions are true. This isn’t how

we normally use “or” in language.

Python Programming, 2/e 10

Page 11: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ The not operator computes the opposite of a Boolean expression.

æ not is a unary operator, meaning it operates on a single expression.

P not P T F F T

Python Programming, 2/e 11

Page 12: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ  We can put these operators together to make arbitrarily complex Boolean expressions.

æ  The interpretation of the expressions relies on the precedence rules for the operators.

Python Programming, 2/e 12

Page 13: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ Consider a or not b and c æ How should this be evaluated? æ The order of precedence, from high to low, is not, and, or.

æ This statement is equivalent to (a or ((not b) and c))

æ Since most people don’t memorize the the Boolean precedence rules, use parentheses to prevent confusion.

Python Programming, 2/e 13

Page 14: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ  To test for the co-location of two points, we could use an and. æ  if p1.getX() == p2.getX() and p2.getY() == p1.getY():

# points are the same else: # points are different

æ  The entire condition will be true only when both of the simpler conditions are true.

Python Programming, 2/e 14

Page 15: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ Say you’re writing a racquetball simulation. The game is over as soon as either player has scored 15 points.

æ How can you represent that in a Boolean expression?

æ  scoreA == 15 or scoreB == 15

æ When either of the conditions becomes true, the entire expression is true. If neither condition is true, the expression is false.

Python Programming, 2/e 15

Page 16: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ  We want to construct a loop that continues as long as the game is not over. æ  You can do this by taking the negation of the game-over condition as your

loop condition!

æ  while not(scoreA == 15 or scoreB == 15): #continue playing

Python Programming, 2/e 16

Page 17: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ  Some racquetball players also use a shutout condition to end the game, where if one player has scored 7 points and the other person hasn’t scored yet, the game is over.

æ  while not(scoreA == 15 or scoreB == 15 or \ (scoreA == 7 and scoreB == 0) or (scoreB == 7 and scoreA == 0): #continue playing

Python Programming, 2/e 17

Page 18: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Operators

æ  Let’s look at volleyball scoring. To win, a volleyball team needs to win by at least two points.

æ  In volleyball, a team wins at 15 points æ  If the score is 15 – 14, play continues, just as it does for 21 – 20. æ  (a >= 15 and a - b >= 2) or (b >= 15 and b - a >= 2) æ  (a >= 15 or b >= 15) and abs(a - b) >= 2

Python Programming, 2/e 18

Page 19: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Algebra

æ  The ability to formulate, manipulate, and reason with Boolean expressions is an important skill.

æ  Boolean expressions obey certain algebraic laws called Boolean logic or Boolean algebra.

Python Programming, 2/e 19

Page 20: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Algebra

æ and has properties similar to multiplication æ or has properties similar to addition æ 0 and 1 correspond to false and true,

respectively.

Python Programming, 2/e 20

Algebra Boolean algebra

a * 0 = 0 a and false == false a * 1 = a a and true == a a + 0 = a a or false == a

Page 21: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Algebra

æ  Anything ored with true is true: a or true == true

æ  Both and and or distribute: a or (b and c) == (a or b) and (a or c) a and (b or c) == (a and b) or (a and c)

æ  Double negatives cancel out: not(not a) == a

æ  DeMorgan’s laws: not(a or b) == (not a) and (not b) not(a and b) == (not a) or (not b)

Python Programming, 2/e 21

Page 22: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Algebra

æ We can use these rules to simplify our Boolean expressions.

æ  while not(scoreA == 15 or scoreB == 15): #continue playing

æ This is saying something like “While it is not the case that player A has 15 or player B has 15, continue playing.”

æ Applying DeMorgan’s law: while (not scoreA == 15) and (not scoreB == 15): #continue playing

Python Programming, 2/e 22

Page 23: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Algebra

æ  This becomes: while scoreA != 15 and scoreB != 15 # continue playing

æ  Isn’t this easier to understand? “While player A has not reached 15 and player B has not reached 15, continue playing.”

Python Programming, 2/e 23

Page 24: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Algebra

æ Sometimes it’s easier to figure out when a loop should stop, rather than when the loop should continue.

æ In this case, write the loop termination condition and put a not in front of it. After a couple applications of DeMorgan’s law you are ready to go with a simpler but equivalent expression.

Python Programming, 2/e 24

Page 25: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

æ  In the quadratic program we used decision structures to avoid taking the square root of a negative number, thus avoiding a run-time error.

æ  This is true for many programs: decision structures are used to protect against rare but possible errors.

Python Programming, 2/e 25

Page 26: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

æ In the quadratic example, we checked the data before calling sqrt. Sometimes functions will check for errors and return a special value to indicate the operation was unsuccessful.

æ E.g., a different square root operation might return a –1 to indicate an error (since square roots are never negative, we know this value will be unique).

Python Programming, 2/e 26

Page 27: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

æ  discRt = otherSqrt(b*b - 4*a*c) if discRt < 0: print("No real roots.“) else: ...

æ Sometimes programs get so many checks for special cases that the algorithm becomes hard to follow.

æ Programming language designers have come up with a mechanism to handle exception handling to solve this design problem.

Python Programming, 2/e 27

Page 28: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

æ  The programmer can write code that catches and deals with errors that arise while the program is running, i.e., “Do these steps, and if any problem crops up, handle it this way.”

æ  This approach obviates the need to do explicit checking at each step in the algorithm.

Python Programming, 2/e 28

Page 29: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

# quadratic5.py # A program that computes the real roots of a quadratic equation. # Illustrates exception handling to avoid crash on bad inputs import math def main(): print("This program finds the real solutions to a quadratic\n") try: a, b, c = eval(input("Please 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) except ValueError: print("\nNo real roots")

Python Programming, 2/e 29

Page 30: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

æ The try statement has the following form: try: <body>

except <ErrorType>: <handler>

æ When Python encounters a try statement, it attempts to execute the statements inside the body.

æ If there is no error, control passes to the next statement after the try…except.

Python Programming, 2/e 30

Page 31: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

æ If an error occurs while executing the body, Python looks for an except clause with a matching error type. If one is found, the handler code is executed.

æ The original program generated this error with a negative discriminant: Traceback (most recent call last): File "C:\Documents and Settings\Terry\My Documents\Teaching\W04\CS120\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 31

Page 32: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

æ The last line, “ValueError: math domain error”, indicates the specific type of error.

æ Here’s the new code in action: This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c): 1, 1, 1 No real roots

æ Instead of crashing, the exception handler prints a message indicating that there are no real roots.

Python Programming, 2/e 32

Page 33: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

æ The try…except can be used to catch any kind of error and provide for a graceful exit.

æ In the case of the quadratic program, other possible errors include not entering the right number of parameters (“unpack tuple of wrong size”), entering an identifier instead of a number (NameError), entering an invalid Python expression (TypeError).

æ A single try statement can have multiple except clauses.

Python Programming, 2/e 33

Page 34: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

Python Programming, 2/e 34

# quadratic6.py import math def main(): print("This program finds the real solutions to a quadratic\n") try: a, b, c = eval(input("Please 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 ) except ValueError as excObj: if str(excObj) == "math domain error": print("No Real Roots") else: print("You didn't give me the right number of coefficients.") except NameError: print("\nYou didn't enter three numbers.") except TypeError: print("\nYour inputs were not all numbers.") except SyntaxError: print("\nYour input was not in the correct form. Missing comma?") except: print("\nSomething went wrong, sorry!") main()

Page 35: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

æ The multiple excepts act like elifs. If an error occurs, Python will try each except looking for one that matches the type of error.

æ The bare except at the bottom acts like an else and catches any errors without a specific match.

æ If there was no bare except at the end and none of the except clauses match, the program would still crash and report an error.

Python Programming, 2/e 35

Page 36: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Exception Handling

æ  Exceptions themselves are a type of object. æ  If you follow the error type with an identifier in an except clause, Python

will assign that identifier the actual exception object.

Python Programming, 2/e 36

Page 37: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Study in Design: Max of Three

æ  Now that we have decision structures, we can solve more complicated programming problems. The negative is that writing these programs becomes harder!

æ  Suppose we need an algorithm to find the largest of three numbers.

Python Programming, 2/e 37

Page 38: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Study in Design: Max of Three

def main():

x1, x2, x3 = eval(input("Please enter three values: "))

# missing code sets max to the value of the largest

print("The largest value is", max)

Python Programming, 2/e 38

Page 39: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 1: Compare Each to All

æ  This looks like a three-way decision, where we need to execute one of the following: max = x1 max = x2 max = x3

æ  All we need to do now is preface each one of these with the right condition!

Python Programming, 2/e 39

Page 40: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 1: Compare Each to All

æ Let’s look at the case where x1 is the largest. æ if x1 >= x2 >= x3: max = x1

æ Is this syntactically correct? •  Many languages would not allow this compound

condition •  Python does allow it, though. It’s equivalent to

x1 ≥ x2 ≥ x3.

Python Programming, 2/e 40

Page 41: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 1: Compare Each to All

æ  Whenever you write a decision, there are two crucial questions: •  When the condition is true, is executing the body of the decision the

right action to take? –  x1 is at least as large as x2 and x3, so assigning max to x1 is OK. –  Always pay attention to borderline values!!

Python Programming, 2/e 41

Page 42: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 1: Compare Each to All

•  Secondly, ask the converse of the first question, namely, are we certain that this condition is true in all cases where x1 is the max? –  Suppose the values are 5, 2, and 4. –  Clearly, x1 is the largest, but does x1 ≥ x2 ≥ x3 hold? –  We don’t really care about the relative ordering of x2 and x3, so we can make two separate tests: x1

>= x2 and x1 >= x3.

Python Programming, 2/e 42

Page 43: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 1: Compare Each to All

æ We can separate these conditions with and! if x1 >= x2 and x1 >= x3:

max = x1

elif x2 >= x1 and x2 >= x3:

max = x2

else:

max = x3

æ We’re comparing each possible value against all the others to determine which one is largest.

Python Programming, 2/e 43

Page 44: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 1: Compare Each to All

æ  What would happen if we were trying to find the max of five values? æ  We would need four Boolean expressions, each consisting of four conditions

anded together. æ  Yuck!

Python Programming, 2/e 44

Page 45: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 2: Decision Tree

æ  We can avoid the redundant tests of the previous algorithm using a decision tree approach.

æ  Suppose we start with x1 >= x2. This knocks either x1 or x2 out of contention to be the max.

æ  If the conidition is true, we need to see which is larger, x1 or x3.

Python Programming, 2/e 45

Page 46: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 2: Decision Tree

Python Programming, 2/e 46

Page 47: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 2: Decision Tree

æ  if x1 >= x2: if x1 >= x3: max = x1 else: max = x3 else: if x2 >= x3: max = x2 else max = x3

Python Programming, 2/e 47

Page 48: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 2: Decision Tree

æ  This approach makes exactly two comparisons, regardless of the ordering of the original three variables.

æ  However, this approach is more complicated than the first. To find the max of four values you’d need if-elses nested three levels deep with eight assignment statements.

Python Programming, 2/e 48

Page 49: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 3: Sequential Processing

æ How would you solve the problem? æ You could probably look at three numbers and

just know which is the largest. But what if you were given a list of a hundred numbers?

æ One strategy is to scan through the list looking for a big number. When one is found, mark it, and continue looking. If you find a larger value, mark it, erase the previous mark, and continue looking.

Python Programming, 2/e 49

Page 50: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 3: Sequential Processing

Python Programming, 2/e 50

Page 51: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 3: Sequential Processing

æ  This idea can easily be translated into Python.

max = x1

if x2 > max: max = x2

if x3 > max: max = x3

Python Programming, 2/e 51

Page 52: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 3: Sequential Programming

æ  This process is repetitive and lends itself to using a loop. æ  We prompt the user for a number, we compare it to our current max, if it is

larger, we update the max value, repeat.

Python Programming, 2/e 52

Page 53: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 3: Sequential Programming

# maxn.py # Finds the maximum of a series of numbers def main(): n = eval(input("How many numbers are there? ")) # Set max to be the first value max = eval(input("Enter a number >> ")) # Now compare the n-1 successive values for i in range(n-1): x = eval(input("Enter a number >> ")) if x > max: max = x print("The largest value is", max)

Python Programming, 2/e 53

Page 54: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Strategy 4: Use Python

æ  Python has a built-in function called max that returns the largest of its parameters.

æ  def main(): x1, x2, x3 = eval(input("Please enter three values: ")) print("The largest value is", max(x1, x2, x3))

Python Programming, 2/e 54

Page 55: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Some Lessons

æ There’s usually more than one way to solve a problem. •  Don’t rush to code the first idea that pops out of your head. Think

about the design and ask if there’s a better way to approach the problem.

•  Your first task is to find a correct algorithm. After that, strive for clarity, simplicity, efficiency, scalability, and elegance.

Python Programming, 2/e 55

Page 56: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Some Lessons

æ  Be the computer. •  One of the best ways to formulate an algorithm is to ask yourself how

you would solve the problem. •  This straightforward approach is often simple, clear, and efficient

enough.

Python Programming, 2/e 56

Page 57: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Some Lessons

æ  Generality is good. •  Consideration of a more general problem can lead to a better solution

for a special case. •  If the max of n program is just as easy to write as the max of three,

write the more general program because it’s more likely to be useful in other situations.

Python Programming, 2/e 57

Page 58: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Some Lessons

æ  Don’t reinvent the wheel. •  If the problem you’re trying to solve is one that lots of other people

have encountered, find out if there’s already a solution for it! •  As you learn to program, designing programs from scratch is a great

experience! •  Truly expert programmers know when to borrow.

Python Programming, 2/e 58

Page 59: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Example: Conditional Program Execution

æ There are several ways of running Python programs. •  Some modules are designed to be run directly. These

are referred to as programs or scripts. •  Others are made to be imported and used by other

programs. These are referred to as libraries. •  Sometimes we want to create a hybrid that can be

used both as a stand-alone program and as a library.

Python Programming, 2/e 59

Page 60: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Example: Conditional Program Execution

æ  When we want to start a program once it’s loaded, we include the line main() at the bottom of the code.

æ  Since Python evaluates the lines of the program during the import process, our current programs also run when they are imported into an interactive Python session or into another Python program.

Python Programming, 2/e 60

Page 61: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Example: Conditional Program Execution

æ  Generally, when we import a module, we don’t want it to execute! æ  In a program that can be either run stand-alone or loaded as a library, the

call to main at the bottom should be made conditional, e.g. if <condition>:

main()

Python Programming, 2/e 61

Page 62: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Example: Conditional Program Execution

æ  Whenever a module is imported, Python creates a special variable in the module called __name__ to be the name of the imported module.

æ  Example: >>> import math >>> math.__name__ 'math'

Python Programming, 2/e 62

Page 63: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Example: Conditional Program Execution

æ  When imported, the __name__ variable inside the math module is assigned the string ‘math’.

æ  When Python code is run directly and not imported, the value of __name__ is ‘__main__’. E.g.: >>> __name__ '__main__'

Python Programming, 2/e 63

Page 64: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Example: Conditional Program Execution

æ To recap: if a module is imported, the code in the module will see a variable called __name__ whose value is the name of the module.

æ When a file is run directly, the code will see the value ‘__main__’.

æ We can change the final lines of our programs to: if __name__ == '__main__': main()

æ Virtually every Python module ends this way!

Python Programming, 2/e 64

Page 65: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Post-Test Loop

æ  Say we want to write a program that is supposed to get a nonnegative number from the user.

æ  If the user types an incorrect input, the program asks for another value. æ  This process continues until a valid value has been entered. æ  This process is input validation.

Python Programming, 2/e 65

Page 66: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Post-Test Loop

æ  repeat get a number from the user until number is >= 0

Python Programming, 2/e 66

Page 67: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Post-Test Loop

æ  When the condition test comes after the body of the loop it’s called a post-test loop.

æ  A post-test loop always executes the body of the code at least once. æ  Python doesn’t have a built-in statement to do this, but we can do it with a

slightly modified while loop.

Python Programming, 2/e 67

Page 68: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Post-Test Loop

æ  We seed the loop condition so we’re guaranteed to execute the loop once. æ  number = -1

while number < 0: number = eval(input("Enter a positive number: "))

æ  By setting number to –1, we force the loop body to execute at least once.

Python Programming, 2/e 68

Page 69: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Post-Test Loop

æ  Some programmers prefer to simulate a post-test loop by using the Python break statement.

æ  Executing break causes Python to immediately exit the enclosing loop. æ  break is sometimes used to exit what looks like an infinite loop.

Python Programming, 2/e 69

Page 70: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Post-Test Loop

æ  The same algorithm implemented with a break: while True: number = eval(input("Enter a positive number: ")) if x >= 0: break # Exit loop if number is valid

æ  A while loop continues as long as the expression evaluates to true. Since True always evaluates to true, it looks like an infinite loop!

Python Programming, 2/e 70

Page 71: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Post-Test Loop

æ  When the value of x is nonnegative, the break statement executes, which terminates the loop.

æ  If the body of an if is only one line long, you can place it right after the :! æ  Wouldn’t it be nice if the program gave a warning when the input was

invalid?

Python Programming, 2/e 71

Page 72: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Post-Test Loop

æ  In the while loop version, this is awkward: number = -1 while number < 0: number = eval(input("Enter a positive number: ")) if number < 0: print("The number you entered was not positive")

æ  We’re doing the validity check in two places!

Python Programming, 2/e 72

Page 73: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Post-Test Loop

æ  Adding the warning to the break version only adds an else statement: while True: number = eval(input("Enter a positive number: ")) if x >= 0: break # Exit loop if number is valid else: print("The number you entered was not positive.")

Python Programming, 2/e 73

Page 74: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Loop and a Half

æ  Stylistically, some programmers prefer the following approach: while True: number = eval(input("Enter a positive number: ")) if x >= 0: break # Loop exit print("The number you entered was not positive")

æ  Here the loop exit is in the middle of the loop body. This is what we mean by a loop and a half.

Python Programming, 2/e 74

Page 75: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Loop and a Half

æ  The loop and a half is an elegant way to avoid the priming read in a sentinel loop.

æ  while True: get next data item if the item is the sentinel: break process the item

æ  This method is faithful to the idea of the sentinel loop, the sentinel value is not processed!

Python Programming, 2/e 75

Page 76: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Loop and a Half

Python Programming, 2/e 76

Page 77: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Loop and a Half

æ  To use or not use break. That is the question! æ  The use of break is mostly a matter of style and taste. æ  Avoid using break often within loops, because the logic of a loop is hard to

follow when there are multiple exits.

Python Programming, 2/e 77

Page 78: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

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":

Python Programming, 2/e 78

Page 79: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions as Decisions

æ Be careful! You can’t take shortcuts: while response[0] == "y" or "Y":

æ Why doesn’t this work? æ Python has a bool type that internally uses 1

and 0 to represent True and False, respectively.

æ The Python condition operators, like ==, always evaluate to a value of type bool.

Python Programming, 2/e 79

Page 80: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions as Decisions

æ  However, Python will let you evaluate any built-in data type as a Boolean. For numbers (int, float, and long ints), zero is considered False, anything else is considered True.

Python Programming, 2/e 80

Page 81: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

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

Python Programming, 2/e 81

Page 82: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

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.

Python Programming, 2/e 82

Page 83: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions as Decisions

Python Programming, 2/e 83

Operator Operational definition

x and y If x is false, return x. Otherwise, return y.

x or y If x is true, return x. Otherwise, return y.

not x If x is false, return True. Otherwise, return False.

Page 84: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions as Decisions

æ  Consider x and y. In order for this to be true, both x and y must be true. æ  As soon as one of them is found to be false, we know the expression as a

whole is false and we don’t need to finish evaluating the expression. æ  So, if x is false, Python should return a false result, namely x.

Python Programming, 2/e 84

Page 85: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions as Decisions

æ  If x is true, then whether the expression as a whole is true or false depends on y.

æ  By returning y, if y is true, then true is returned. If y is false, then false is returned.

Python Programming, 2/e 85

Page 86: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions as Decisions

æ  These definitions show that Python’s Booleans are short-circuit operators, meaning that a true or false is returned as soon as the result is known.

æ  In an and where the first expression is false and in an or, where the first expression is true, Python will not evaluate the second expression.

Python Programming, 2/e 86

Page 87: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions as Decisions

æ  response[0] == "y" or "Y“

æ The Boolean operator is combining two operations.

æ Here’s an equivalent expression: (response[0] == "y") or ("Y")

æ By the operational description of or, this expression returns either True, if response[0] equals “y”, or “Y”, both of which are interpreted by Python as true.

Python Programming, 2/e 87

Page 88: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

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.

Python Programming, 2/e 88

Page 89: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions as Decisions

æ  ans = input("What flavor fo 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.

Python Programming, 2/e 89

Page 90: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions as Decisions

æ  We can code this even more succinctly! ans = input("What flavor fo you want [vanilla]: ") flavor = ans or "vanilla“

æ  Remember, any non-empty answer is interpreted as True. æ  This exercise could be boiled down into one line!

flavor = input("What flavor do you want [vanilla]:” ) or "vanilla"

Python Programming, 2/e 90

Page 91: Python Programming: An Introduction To Computer Science · Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e

The University of Western Australia

Boolean Expressions as Decisions

æ  Again, if you understand this method, feel free to utilize it. Just make sure that if your code is tricky, that it’s well documented!

Python Programming, 2/e 91