1/26/2025
Module 3: Decision
ITM200 – FUNDAMENTALS OF PROGRAMMING
WINTER 2025
Contents
• The if Statement
• Relational Operators
• Nested Branches (Conditionals)
• Chained Conditionals
• Boolean Variables and Operators
• Comparing and Analyzing Strings
1/26/2025 2
1
1/26/2025
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.
1/26/2025 3
Flowchart of the if Statement
• One of the two branches is executed once
• True (if) branch or False (else) branch
1/26/2025 4
2
1/26/2025
Flowchart with only a True Branch
• An if statement may not need a ‘False’ (else) branch
1/26/2025 5
Syntax 3.1: The if Statement
1/26/2025 6
3
1/26/2025
Elevator Simulation
1/26/2025 7
Our First Example
• 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?
1/26/2025 8
4
1/26/2025
Our First Example – for lab session
• Revised Problem Statement (I):
• Check the input entered by the user:
• If the input is 13, set the value to 14 and print a message
• Modify the elevator simulation program to test the input
The relational operator for equal is “==“
• Modified Problem Statement (II)
• In some countries the number 14 is considered unlucky.
• What is the revised algorithm?
• Modify the elevator simulation program to “skip” both the 13th and
14th floor
1/26/2025 9
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
1/26/2025 10
10
5
1/26/2025
Compound Statements
• Statement blocks can be nested inside other types of blocks.
• 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
1/26/2025 11
11
Tips on Indenting Blocks
• Let an IDE do the indenting for you…
This is referred to as “block structured” code. Indenting consistently is not
only syntactically required in Python, it also makes code much easier to
follow.
1/26/2025 12
12
6
1/26/2025
A Common Error
• Avoid duplication in branches
• If the same code is duplicated in each branch then move it out of the
if statement.
1/26/2025 13
13
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 :
..
1/26/2025 14
14
7
1/26/2025
Assignment vs. Equality Testing
• Assignment: makes something true.
floor = 13
• Equality testing: checks if something is true.
if floor == 13 :
1/26/2025 15
15
Comparing Strings
• Checking if two strings are equal
if name1 == name2 :
print("The strings are identical")
• Checking if two strings are not equal
if name1 != name2 :
print("The strings are not identical")
1/26/2025 16
16
8
1/26/2025
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:
1/26/2025 17
17
Checking for String Equality (2)
• If any character is different, the two strings will not be equal:
1/26/2025 18
18
9
1/26/2025
Relational Operator Examples (1)
1/26/2025 19
19
Relational Operator Examples (2)
1/26/2025 20
20
10
1/26/2025
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.
• For example, the following code multiplies the square root of 2 by itself.
• Ideally, we expect to get the answer 2:
r = [Link](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
1/26/2025 21
21
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 = [Link](2.0)
if abs(r * r - 2.0) < EPSILON :
print("sqrt(2.0) squared is approximately 2.0")
1/26/2025 22
22
11
1/26/2025
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
• Refer to the Basic Latin (ASCII) Subset of Unicode
1/26/2025 23
23
Basic Latin (ASCII) subset of Unicode
1/26/2025 24
24
12
1/26/2025
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
if floor > height + 1 :
1/26/2025 25
25
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.
if originalPrice < 128 :
discountRate = 0.92
else :
discountRate = 0.84
discountedPrice = discountRate * originalPrice
• 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?
1/26/2025 26
26
13
1/26/2025
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
1/26/2025 27
27
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
1/26/2025 28
28
14
1/26/2025
Tax Example: nested ifs
• Four outcomes (branches)
• Single
• <= 32000
• > 32000
• Married
• <= 64000
• > 64000
1/26/2025 29
29
Flowchart for the Tax Example
• Four branches
1/26/2025 30
30
15
1/26/2025
Federal Tax (1)
1/26/2025 31
31
Federal Tax (2)
• The ‘True’ branch (Single)
• Two branches within this branch
1/26/2025 32
32
16
1/26/2025
Federal Tax (3)
• The ‘False’ branch (Married)
1/26/2025 33
33
Running the Federal Tax Example
• 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?
1/26/2025 34
34
17
1/26/2025
Chained Conditionals
1/26/2025 35
35
Chained Conditionals
• 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
When using multiple if statements,
test the general conditions after the
more specific conditions.
1/26/2025 36
36
18
1/26/2025
Flowchart of Chained Conditioners
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
1/26/2025 37
37
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
1/26/2025 38
38
19
1/26/2025
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")
• Run the program with several different inputs
1/26/2025 39
39
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")
1/26/2025 40
40
20
1/26/2025
Boolean Variables and
Operators
1/26/2025 41
41
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
1/26/2025 42
42
21
1/26/2025
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
if temp > 0 and temp < 100 :
print("Liquid")
1/26/2025 43
43
Combined Conditions: or
• We use or if only one of two conditions need to be true
• Use a compound conditional with an or:
if temp <= 0 or temp >= 100
:
print("Not liquid")
• If either condition is true
• The result is true
1/26/2025 44
44
22
1/26/2025
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?")
if attending and not(grade < 60) :
print("Stay")
• If you are using not, try to use simpler logic:
if attending and grade >= 60 :
print("Stay")
1/26/2025 45
45
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 :
1/26/2025 46
46
23
1/26/2025
Comparison of Numbers
• Run the program with several inputs
1/26/2025 47
47
Boolean Operator Examples
1/26/2025 48
48
24
1/26/2025
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.
1/26/2025 49
49
Catching Exceptions using try and except
• Here is a sample program to convert a Fahrenheit temperature to a
Celsius temperature:
• We can rewrite our temperature converter as follows:
1/26/2025 50
50
25
1/26/2025
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?
if temp > 0 and temp < 100 :
print("Liquid")
Done!
1/26/2025 51
51
Short-circuit evaluation: or
• If the left half of the or is true, why look further?
if temp <= 0 or temp >= 100 :
print("Not Liquid")
Done!
1/26/2025 52
52
26
1/26/2025
Analyzing Strings
1/26/2025 53
53
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
1/26/2025 54
54
27
1/26/2025
Substring: Suffixes
• Suppose you are given the name of a file and need to ensure that it
has the correct extension
if [Link](".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.
1/26/2025 55
55
Operations for Testing Substrings
1/26/2025 56
56
28
1/26/2025
Methods: Testing String Characteristics (1)
1/26/2025 57
57
Methods for Testing String Characteristics (2)
1/26/2025 58
58
29
1/26/2025
Comparing and Analyzing Strings
1/26/2025 59
59
Substring Example
The itsy bitsy spider went up the water spout
itsy
1/26/2025 60
60
30
1/26/2025
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 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.
1/26/2025 61
61
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.
1/26/2025 62
62
31
1/26/2025
Summary: String
• Sometimes it is necessary to determine if a string contains a given
substring.
• There are several operation for testing substrings.
• There are several methods to compare and analyze strings.
1/26/2025 63
63
Lab Tasks
• Review the examples.
• How do you test whether exactly one of two integers is zero?
• Enter the values of the lengths of three sides, judge if the three sides
can construct a triangle. If yes, tell us if it is an equilateral one, an
isosceles one, scalene one, a right one, an acute one or an obtuse one.
1/26/2025 64
64
32