Python Programming: An Introduction To Computer Science



Similar documents
Python Programming: An Introduction to Computer Science

Python Loops and String Manipulation

for while ' while ' for * for <var> in <sequence>: <body> $ %%" 0 *0

Introduction to Python

Writing Simple Programs

Exercise 4 Learning Python language fundamentals

A Quick Algebra Review

How To Understand The Details Of A Function In Python (For Beginners)

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Introduction to Python

CSC 221: Computer Programming I. Fall 2011

Visual Logic Instructions and Assignments

Cal Answers Analysis Training Part I. Creating Analyses in OBIEE

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Exercise 1: Python Language Basics

Chapter 5. Selection 5-1

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Math Review. for the Quantitative Reasoning Measure of the GRE revised General Test

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

SOLVING QUADRATIC EQUATIONS - COMPARE THE FACTORING ac METHOD AND THE NEW DIAGONAL SUM METHOD By Nghi H. Nguyen

Calculator. Introduction. Requirements. Design. The calculator control system. F. Wagner August 2009

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

Object Oriented Software Design

Welcome to Math Video Lessons. Stanley Ocken. Department of Mathematics The City College of New York Fall 2013

COLLEGE ALGEBRA. Paul Dawkins

Conditionals: (Coding with Cards)

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Selection Statements

Object Oriented Software Design

If A is divided by B the result is 2/3. If B is divided by C the result is 4/7. What is the result if A is divided by C?

Factoring Polynomials and Solving Quadratic Equations

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

if and if-else: Part 1

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

SECTION 0.6: POLYNOMIAL, RATIONAL, AND ALGEBRAIC EXPRESSIONS

Welcome to Introduction to programming in Python

Problem Solving Basics and Computer Programming

Moving from CS 61A Scheme to CS 61B Java

Decision Logic: if, if else, switch, Boolean conditions and variables

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Math 25 Activity 6: Factoring Advanced

Copyrighted Material. Chapter 1 DEGREE OF A CURVE

CHAPTER 7 GENERAL PROOF SYSTEMS

Python Basics. S.R. Doty. August 27, Preliminaries What is Python? Installation and documentation... 4

Chapter 8 Selection 8-1

River Dell Regional School District. Computer Programming with Python Curriculum

COMP 110 Prasun Dewan 1

Python Evaluation Rules

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

6. Control Structures

Computer Programming I

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Beating Roulette? An analysis with probability and statistics.

1 Using a SQL Filter in Outlook 2002/2003 Views. 2 Defining the Problem The Task at Hand

PGR Computing Programming Skills

Python Programming: An Introduction to Computer Science

LEARNING TO PROGRAM WITH PYTHON. Richard L. Halterman

CHAPTER 2. Logic. 1. Logic Definitions. Notation: Variables are used to represent propositions. The most common variables used are p, q, and r.

USC Marshall School of Business Marshall Information Services

Appendix: Tutorial Introduction to MATLAB

A positive exponent means repeated multiplication. A negative exponent means the opposite of repeated multiplication, which is repeated

0 Introduction to Data Analysis Using an Excel Spreadsheet

Flowcharting, pseudocoding, and process design

Numerical and Algebraic Fractions

Factoring Polynomials

MBA Jump Start Program

CHAPTER 18 Programming Your App to Make Decisions: Conditional Blocks

6.042/18.062J Mathematics for Computer Science. Expected Value I

No Solution Equations Let s look at the following equation: 2 +3=2 +7

How to Study Mathematics Written by Paul Dawkins

CS 111 Classes I 1. Software Organization View to this point:

December 4, 2013 MATH 171 BASIC LINEAR ALGEBRA B. KITCHENS

11 Ideals Revisiting Z

Concepts in IP Addressing...

Math 4310 Handout - Quotient Vector Spaces

Recovering from a System Crash

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

How to open an account

1.3 Algebraic Expressions

Iteration CHAPTER 6. Topic Summary

Solving systems by elimination

Mathematics for Computer Science/Software Engineering. Notes for the course MSM1F3 Dr. R. A. Wilson

ALGORITHMS AND FLOWCHARTS

Computer Science for San Francisco Youth

Introduction to Python for Text Analysis

Interactive Applications (CLI) and Math

Algebra Practice Problems for Precalculus and Calculus

Polynomials and Factoring. Unit Lesson Plan

WHAT ARE MATHEMATICAL PROOFS AND WHY THEY ARE IMPORTANT?

0.8 Rational Expressions and Equations

Crash Dive into Python

MATLAB Programming. Problem 1: Sequential

Transcription:

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

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

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

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

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

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

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. P Q P and Q T T T T F F F T F F F F 7

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

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 9

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

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 T F not P F T 11

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

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

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

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

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 16

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 17

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 18

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

Boolean Algebra Algebra a * 0 = 0 a * 1 = a a + 0 = a Boolean algebra a and false == false a and true == a a or false == a æ and has properties similar to multiplication æ or has properties similar to addition æ 0 and 1 correspond to false and true, respectively. 20

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

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 22

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

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

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

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

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

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

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

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

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

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

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

Exception Handling # 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() 34

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

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

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

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

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

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

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

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

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: else: max = x2 max = x3 æ We re comparing each possible value against all the others to determine which one is largest. 43

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

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

Strategy 2: Decision Tree 46

Strategy 2: Decision Tree æ if x1 >= x2: if x1 >= x3: max = x1 else: max = x3 else: if x2 >= x3: max = x2 else max = x3 47

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

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

Strategy 3: Sequential Processing 50

Strategy 3: Sequential Processing æ This idea can easily be translated into Python. max = x1 if x2 > max: max = x2 if x3 > max: max = x3 51

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

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

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

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

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

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

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

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

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

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

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' 62

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

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

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

Post-Test Loop æ repeat get a number from the user until number is >= 0 66

Post-Test Loop æ When the condition test comes after the body of the loop it s called a posttest 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. 67

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

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

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

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

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

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

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

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

Loop and a Half 76

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

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

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

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

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 81

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

Boolean Expressions as Decisions 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. 83

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

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

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

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

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

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

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

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