Chapter 03
Chapter 03
PARTE 1: DECISIONI
Chapter Goals
• To implement decisions using the if statement
• To compare integers, floating-point numbers, and Strings
• To write statements using the Boolean data type
• To develop strategies for testing your programs
• To validate user input
In this chapter, you will learn how to program simple and complex
decisions. You will apply what you learn to the task of checking
user input.
9/7/2023 2
Contents
• The if Statement
• Relational Operators
• Nested Branches
• Multiple Alternatives
• Problem Solving: Flowcharts
• Problem Solving: Test Cases
• Boolean Variables and Operators
• Analyzing Strings
• Application: Input Validation
9/7/2023 3
The if Statement
• A computer program often needs to make decisions based on input, or
circumstances
• For example, buildings often ‘skip’ the 13th floor, and elevators should
too
• The 14th floor is really the 13th floor
• So every floor above 12 is really ‘floor - 1’
• If floor > 12, Actual floor = floor - 1
• The two keywords of the if statement are:
• if
• else
The if statement allows a program to
carry out different actions depending on
the nature of the data to be processed.
9/7/2023 4
Flowchart of the if Statement
• One of the two branches is executed once
• True (if) branch or False (else) branch
9/7/2023 5
Flowchart with only a True Branch
• An if statement may not need a ‘False’ (else) branch
9/7/2023 6
Syntax 3.1: The if Statement
9/7/2023 7
Elevatorsim.py
9/7/2023 8
Our First Example
• Open the file:
• elevatorsim.py
• This is a slightly modified program
• Run the program
• Try a value that is less that 13
• What is the result?
• Run the program again with a value that is greater than 13
• What is the result?
• What happens if you enter 13?
9/7/2023 9
Our First Example (2)
• Revised Problem Statement (1):
• Check the input entered by the user:
• If the input is 13, set the value to 14 and print a message
• Modify the elevatorsim program to test the input
The relational operator for equal is “==“
• Modified Problem Statement (2)
• In some countries the number 14 is considered unlucky.
• What is the revised algorithm?
• Modify the elevatorsim program to “skip” both the 13th and 14th
floor
9/7/2023 10
Compound Statements
• Some constructs in Python are compound statements.
• compound statements span multiple lines and consist of a header and
a statement block
The if statement is an example of a compound statement
• Compound statements require a colon “:” at the end of the header.
• The statement block is a group of one or more statements, all indented
to the same column
• The statement block starts on the line after the header and ends at
the first statement indented less than the first statement in the block
9/7/2023 11
Compound Statements
• Statement blocks can be nested inside other types of blocks (we will
learn about more blocks later)
• Statement blocks signal that one or more statements are part of a
given compound statement
• In the case of the if construct the statement block specifies:
• The instructions that are executed if the condition is true
• Or skipped if the condition is false
Statement blocks are visual cues that allow you to follow the login and
flow of a program
9/7/2023 12
Tips on Indenting Blocks
• Let Wing do the indenting for you…
9/7/2023 13
A Common Error
• Avoid duplication in branches
• If the same code is duplicated in each branch then move it out of the
if statement.
9/7/2023 14
The Conditional Operator
• A “shortcut” you may find in existing code
• It is not used in this book
• The shortcut notation can be used anywhere that a value is
expected
Complexity is BAD….
This “shortcut” is difficult to read and a poor programming practice
9/7/2023 15
Relational Operators
• Every if statement has a condition
• Usually compares two values with an operator
if floor > 13 :
..
if floor >= 13 :
..
if floor < 13 :
..
if floor <= 13 :
..
if floor == 13 :
..
9/7/2023 16
Assignment vs. Equality Testing
• Assignment: makes something true.
floor = 13
9/7/2023 17
Comparing Strings
• Checking if two strings are equal
if name1 == name2 :
print("The strings are identical")
if name1 != name2 :
print("The strings are not identical")
9/7/2023 18
Checking for String Equality (1)
• For two strings to be equal, they must be of the same length and
contain the same sequence of characters:
9/7/2023 19
Checking for String Equality (2)
• If any character is different, the two strings will not be equal:
9/7/2023 20
Relational Operator Examples (1)
9/7/2023 21
Relational Operator Examples (2)
9/7/2023 22
Another Example
• Open the file:
• compare.py
• Run the program
• What are the results?
9/7/2023 23
Common Error (Floating Point)
• Floating-point numbers have only a limited precision, and calculations
can introduce roundoff errors.
• You must take these inevitable roundoffs into account when
comparing floating point numbers.
9/7/2023 24
Common Error (Floating Point, 2)
• For example, the following code multiplies the square root of 2 by
itself.
• Ideally, we expect to get the answer 2:
r = math.sqrt(2.0)
if r * r == 2.0 :
print("sqrt(2.0) squared is 2.0")
else :
print("sqrt(2.0) squared is not 2.0 but", r * r)
Output:
sqrt(2.0) squared is not 2.0 but 2.0000000000000004
9/7/2023 25
The Use of EPSILON
• Use a very small value to compare the difference to determine if
floating-point values are ‘close enough’
• The magnitude of their difference should be less than some
threshold
• Mathematically, we would write that x and y are close enough if:
EPSILON = 1E-14
r = math.sqrt(2.0)
if abs(r * r - 2.0) < EPSILON :
print("sqrt(2.0) squared is approximately 2.0")
9/7/2023 26
Lexicographical Order
• To compare Strings in ‘dictionary’ like order:
string1 < string2
• Notes
• All UPPERCASE letters come before lowercase
• ‘space’ comes before all other printable characters
• Digits (0-9) come before all letters
• See Appendix A for the Basic Latin (ASCII) Subset of Unicode
9/7/2023 27
Operator Precedence
• The comparison operators have lower precedence than arithmetic
operators
• Calculations are done before the comparison
• Normally your calculations are on the ‘right side’ of the comparison
or assignment operator
Calculations
actualFloor = floor + 1
9/7/2023 28
Implementing an if Statement (1)
9/7/2023 29
Implementing an if Statement (2)
5) Remove duplication
9/7/2023 30
Implementing an if Statement (3)
7. Write the code in Python
9/7/2023 31
A Third Example
• The university bookstore has a Kilobyte Day sale every October 24
(10.24), giving an 8 percent discount on all computer accessory
purchases if the price is less than $128, and a 16 percent discount if
the price is at least $128.
9/7/2023 32
The Sale Example
• Open the file:
• sale.py
• Run the program several time using different values
• Use values less than 128
• Use values greater that 128
• Enter 128
• What results do you get?
9/7/2023 33
Nested Branches
• You can nest an if inside either branch of an if statement.
• Simple example: Ordering drinks
• Ask the customer for their drink order
• if customer orders wine
• Ask customer for ID
• if customer’s age is 21 or over
• Serve wine
• Else
• Politely explain the law to the customer
• Else
• Serve customers a non-alcoholic drink
9/7/2023 34
Flowchart of a Nested if
Ask for order • Nested if-else inside true branch of
an if statement.
• Three paths
True
Wine? Check ID
False True
>=
Serve wine
21?
Serve non-
alcoholic False
drink Read law
Done
9/7/2023 35
Tax Example: nested ifs
• Four outcomes (branches)
• Single
• <= 32000
• > 32000
• Married
• <= 64000
• > 64000
9/7/2023 36
Flowchart for the Tax Example
• Four branches
9/7/2023 37
Taxes.py (1)
9/7/2023 38
Taxes.py (2)
• The ‘True’ branch (Single)
• Two branches within this branch
9/7/2023 39
Taxes.py (3)
• The ‘False’ branch (Married)
9/7/2023 40
Running the Tax Example
• Open the file:
• taxes.py
• Run the program several time using different values for income and
marital status
• Use income values less than $32,000
• Use income values greater than $64,000
• Enter “&” as the marital status
• What results do you get?
9/7/2023 41
Hand-tracing
• Hand-tracing helps you understand whether a program works correctly
• Create a table of key variables
• Use pencil and paper to track their values
• Works with pseudocode or code
• Track location with a marker
• Use example input values that:
• You know what the correct outcome should be
• Will test each branch of your code
9/7/2023 42
Hand-tracing the Tax Example
• Setup
• Table of variables
• Initial values
9/7/2023 43
Hand-tracing the Tax Example (2)
• Input variables
• From user
• Update table
9/7/2023 44
Hand-tracing the Tax Example (3)
• Because income is not <= 64000, we move to the else clause on line 28
• Update variables on lines 29 and 30
• Use constants
9/7/2023 45
Incremental Code and Test
• Using the flag problem statement as an example:
• Compute the data for the first panel
• Print out the data
• Color
• The X and Y coordinates of the top left corner of the panel
• The width of the panel
• The height of the panel
• Check the data
• If the data is correct:
• Draw the panel
• Else
• Look at your equations
• Find and fix any errors
• Check the data again
• Do the next panel
9/7/2023 46
Alternative multiple
9/7/2023 47
3.4 Multiple Alternatives
• What if you have more than two branches?
• Count the branches for the following earthquake effect example:
• 8 (or greater)
• 7 to 7.99
• 6 to 6.99
• 4.5 to 5.99
• Less than 4.5
9/7/2023 48
Flowchart of Multiway Branching
True
>= 8.0? Most Structures Fall
False
True
>= 7.0? Many Buildings Destroyed
False
True Many buildings considerably damaged,
>= 6.0?
some collapse
False
True
>= 4.5? Damage to poorly constructed buildings
False
No destruction of buildings
9/7/2023 49
elif Statement
• Short for Else, if…
• As soon as one on the test conditions succeeds, the statement block is
executed
• No other tests are attempted
• If none of the test conditions succeed the final else clause is executed
9/7/2023 50
if, elif Multiway Branching
if richter >= 8.0 : # Handle the ‘special case’ first
print("Most structures fall")
elif richter >= 7.0 :
print("Many buildings destroyed")
elif richter >= 6.0 :
print("Many buildings damaged, some collapse")
elif richter >= 4.5 :
print("Damage to poorly constructed buildings")
else : # so that the ‘general case’ can be handled last
print("No destruction of buildings")
9/7/2023 51
What is Wrong With This Code?
if richter >= 8.0 :
print("Most structures fall")
if richter >= 7.0 :
print("Many buildings destroyed")
if richter >= 6.0 :
print("Many buildings damaged, some collapse")
if richter >= 4.5 :
print("Damage to poorly constructed buildings")
9/7/2023 52
earthquake Example
• Open the file:
• earthquake.py
• Run the program with several different inputs
9/7/2023 53
Using Flowcharts to Develop
and Refine Algorithms
9/7/2023 54
3.5 Problem Solving: Flowcharts
• You have seen a few basic flowcharts
• A flowchart shows the structure of decisions and tasks to solve a
problem
• Basic flowchart elements:
9/7/2023 55
Using Flowcharts
• Flowcharts are an excellent tool
• They can help you visualize the flow of your algorithm
• Building the flowchart
• Link your tasks and input / output boxes in the sequence they need
to be executed
• When you need to make a decision use the diamond (a conditional
statement) with two outcomes
• Never point an arrow inside another branch
9/7/2023 56
Conditional Flowcharts
Two Outcomes Multiple Outcomes
9/7/2023 57
Shipping Cost flowchart
Shipping costs are $5 inside the contiguous the United States (Lower 48
states), and $10 to Hawaii and Alaska. International shipping costs are
also $10.
• Three Branches:
9/7/2023 58
Don’t Connect Branches!
Shipping costs are $5 inside the United States, except that to Hawaii and
Alaska they are $10. International shipping costs are also $10.
• Don’t do this!
9/7/2023 59
Shipping Cost Flowchart
Shipping costs are $5 inside the United States, except that to Hawaii and
Alaska they are $10. International shipping costs are also $10.
9/7/2023 60
Shipping Example
• Open the file:
• Shipping.py
• Run the program with several different inputs?
• What happens if you enter “usa” as the country?
• We will learn several ways to correct the code later in this
chapter
9/7/2023 61
Complex Decision Making is Hard
• Computer systems are used to help sort and route luggage at airports
• The systems:
• Scan the baggage tags
• Sorts the items
• Routes the items to conveyor belts
• Humans then place the bags on trucks
• In 1993 Denver built a new airport with a “state of the art” luggage
system that replaced the human operators with robotic carts
• The system failed
• The airport could not open with out a luggage system
• The system was replaced (it took over a year)
• The cost was almost $1B…. (yes one billion… 1994 dollars)
• The company that designed the system went bankrupt
9/7/2023 62
Building Test Cases
9/7/2023 63
Problem Solving: Test Cases
• Aim for complete coverage of all decision points:
• There are two possibilities for the marital status and two tax
brackets for each status, yielding four test cases
• Test a handful of boundary conditions, such as an income that is at
the boundary between two tax brackets, and a zero income
• If you are responsible for error checking (which is discussed in
Section 3.9), also test an invalid input, such as a negative income
• Each branch of your code should be covered with a test case
9/7/2023 64
Choosing Test Cases
• Choose input values that:
• Test boundary cases and 0 values
• Test each branch
9/7/2023 65
Make a Schedule…
• Make a reasonable estimate of the time it will take you to:
• Design the algorithm
• Develop test cases
• Translate the algorithm to code and enter the code
• Test and debug your program
• Leave some extra time for unanticipated problems
As you gain more experience your estimates will become more
accurate. It is better to have some extra time than to be late
9/7/2023 66
Boolean Variables and
Operators
9/7/2023 67
Boolean Variables
• Boolean Variables
• A Boolean variable is often called a flag because it can be either up
(true) or down (false)
• boolean is a Python data type
• failed = True
• Boolean variables can be either True or False
• There are two Boolean Operators: and, or
• They are used to combine multiple conditions
9/7/2023 68
Combined Conditions: and
• Combining two conditions is often used in range checking
• Is a value between two other values?
• Both sides of the and must be true for the result to be true
9/7/2023 69
Combined Conditions: or
• We use or if only one of two conditions need to be true
• Use a compound conditional with an or:
9/7/2023 70
The not operator: not
• If you need to invert a boolean variable or comparison, precede it with
not
if not attending or grade < 60 :
print("Drop?")
9/7/2023 71
The not operator: inequality !
• A slightly different operator is used for the not when checking for
inequality rather than negation.
• Example inequality:
• The password that the user entered is not equal to the password on
file.
• if userPassword != filePassword :
9/7/2023 72
and Flowchart
• This is often called ‘range checking’
• Used to validate that the input is
between two values
9/7/2023 73
or flowchart
• Another form of ‘range checking’
• Checks if value is outside a range
9/7/2023 74
Comparison Example
• Open the file:
• Compare2.py
• Run the program with several inputs
9/7/2023 75
Boolean Operator Examples
9/7/2023 76
Common Errors with Boolean Conditions
Confusing and and or Conditions
• It is a surprisingly common error to confuse and and or conditions.
• A value lies between 0 and 100 if it is at least 0 and at most 100.
• It lies outside that range if it is less than 0 or greater than 100.
• There is no golden rule; you just have to think carefully.
9/7/2023 77
Short-circuit Evaluation: and
• Combined conditions are evaluated from left to right
• If the left half of an and condition is false, why look further?
Done!
9/7/2023 78
Short-circuit evaluation: or
• If the left half of the or is true, why look further?
Done!
9/7/2023 79
De Morgan’s law
• De Morgan’s law tells you how to negate and and or conditions:
• not(A and B) is the same as notA or notB
• not(A or B) is the same as notA and notB
• Example: Shipping is higher to AK and HI
9/7/2023 80
Analisi di stringhe
9/7/2023 81
Analyzing Strings – The in Operator
• Sometimes it’s necessary to analyze or ask certain questions about a
particular string.
• Sometimes it is necessary to determine if a string contains a given
substring. That is, one string contains an exact match of another
string.
• Given this code segment,
name = "John Wayne"
• the expression
"Way" in name
• yields True because the substring "Way" occurs within the string
stored in variable name.
• The not in operator is the inverse on the in operator
9/7/2023 82
Substring: Suffixes
• Suppose you are given the name of a file and need to ensure that it
has the correct extension
if filename.endswith(".html") :
print("This is an HTML file.")
• The endswith() string method is applied to the string stored in
filename and returns True if the string ends with the substring
".html" and False otherwise.
9/7/2023 83
Operations for Testing Substrings
9/7/2023 84
Methods: Testing String Characteristics (1)
9/7/2023 85
Methods for Testing String Characteristics (2)
9/7/2023 86
Comparing and Analyzing Strings (1)
9/7/2023 87
Comparing and Analyzing Strings (2)
9/7/2023 88
Substring Example
• Open the file:
• Substrings.ph
• Run the program and test several strings and substrings
9/7/2023 89
Input Validation
9/7/2023 90
Input Validation
• Accepting user input is dangerous
• Consider the Elevator program:
• Assume that the elevator panel has buttons labeled 1 through 20
(but not 13).
9/7/2023 91
Input Validation
• The following are illegal inputs:
• The number 13
if floor == 13 :
print("Error: There is no thirteenth floor.")
9/7/2023 92
Elevatorsim2.py
9/7/2023 93
Elevator Simulation
• Open the file:
• elevatorsim2.py
• Test the program with a range of inputs including:
• 12
• 14
• 13
• -1
• 0
• 23
• 19
9/7/2023 94
Chapter Three Review
9/7/2023 95
Summary: if Statement
• The if statement allows a program to carry out different actions
depending on the nature of the data to be processed.
• Relational operators ( < <= > >= == != ) are used to compare
numbers and Strings.
• Strings are compared in lexicographic order.
• Multiple if statements can be combined to evaluate complex
decisions.
• When using multiple if statements, test general conditions after
more specific conditions.
9/7/2023 96
Summary: Flowcharts and Testing
• When a decision statement is contained inside the branch of another
decision statement, the statements are nested.
• Nested decisions are required for problems that have two levels of
decision making.
• Flow charts are made up of elements for tasks, input/output, and
decisions.
• Each branch of a decision can contain tasks and further decisions.
• Never point an arrow inside another branch.
• Each branch of your program should be covered by a test case.
• It is a good idea to design test cases before implementing a program.
9/7/2023 97
Summary: Boolean
• The type boolean has two values, true and false.
• Python has two Boolean operators that combine conditions: and
and or.
• To invert a condition, use the not operator.
• When checking for equality use the ! operator.
• The and and or operators are computed lazily:
• As soon as the truth value is determined, no further conditions
are evaluated.
• De Morgan’s law tells you how to negate and and or conditions.
9/7/2023 98