Chapter 3
Decisions
Dr. Asma Wasfi
Computer Programming - GENG 230 1
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
Computer Programming - GENG 230 2
Outline
3.1 The if Statement
3.2 Relational Operators
3.3 Nested Branches
3.4 Multiple Alternatives
3.7 Boolean Variables and Operators
3.8 Analyzing Strings
3.9 Application: Input Validation
Computer Programming - GENG 230 3
3.1 The if Statement
Computer Programming - GENG 230 4
3.1 The if statement
q A computer program often needs to make decisions based on input, or circumstances
q The two keywords of the if statement are:
o if
o else
q Two methods to use if statement:
If conditions: # if the condition is true, then, execute statements. Otherwise, skip statement
statement
Or
If conditions: # if the condition is true, then, execute statement1. Otherwise, execute statement2
statement1
else
statement2
q The conditions are usually written using relational and logical operators such as: <, >, <=, and, or
Computer Programming - GENG 230 5
3.1 The if statement
Flowchart of the if Statement
Ø 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
True (if) branch or False (else) branch
Computer Programming - GENG 230 6
3.1 The if statement
Flowchart with only a True Branch
Ø An if statement may not need a ‘False’ (else) branch
Computer Programming - GENG 230 7
3.1 The if statement
Computer Programming - GENG 230 8
3.1 The if statement: Elevator Example
Computer Programming - GENG 230 9
3.1 The if statement: Practice Example
q Write a python program to check if the number is divisible by 5 or not
number = int(input("Enter a number: "))
if (number%5 == 0):
print("Number is divisible by 5")
else:
print("Number is not divisible by 5")
q Exercise: Write a python program to check if the number is odd or even
number = int(input("Enter a number: "))
if number%2 == 0:
print("Given number is Even")
else:
print("Given number is Odd")
Computer Programming - GENG 230 10
Compound Statement
q Some constructs in Python are compound statements.
q compound statements span multiple lines and consist of a header and a statement
block
q The if statement is an example of a compound statement
q Compound statements require a colon “:” at the end of the header.
q The statement block is a group of one or more statements, all indented to the
same column
q 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
x=7
y=9
if x > 5:
x = x + 5
y = y + 1
print("x= ", x , "y= ", y) #output x=12 y=10
Computer Programming - GENG 230 11
Compound Statement
Computer Programming - GENG 230 12
The Conditional Operator
q A “shortcut” for the if else statement
q statement1 if condition else statement2
print("Good Morning") if time <12 else print("Good evening")
True branch Condition False branch
print("Good Morning") if time <12 else print("Good evening")
Computer Programming - GENG 230 13
3.2 Relational Operators
Computer Programming - GENG 230 14
3.2 Relational Operators
q Every if statement has a condition
q Usually compares two values with an operator
Hint: Do not mix between python == and math notation =
if floor > 13 :
..
if floor >= 13 :
..
if floor < 13 :
..
if floor <= 13 :
..
if floor == 13 :
..
Computer Programming - GENG 230 15
Assignment vs Equality Testing
q Assignment: makes something true.
x = 12
q Equality testing: checks if something is true.
x == 12
Computer Programming - GENG 230 16
Comparing Strings
q Checking if two strings are equal
if name1 == name2 :
print("The strings are identical")
q Checking if two strings are not equal
if name1 != name2 :
print("The strings are not identical")
q For two strings to be equal, they must be of the same length and contain the same se
quence of characters:
name1 = A H M A D S A I D !
name2 = A H M A D S A I D !
Computer Programming - GENG 230 17
Comparing Strings
q If any character is different, the two strings will not be equal:
Computer Programming - GENG 230 18
Relational Operator Examples
Computer Programming - GENG 230 19
Common Error (Floating Point)
q Floating-point numbers have only a limited precision, and calculations can introduce roundoff errors.
q You must take these inevitable roundoffs into account when comparing floating point numbers.
import math
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
Computer Programming - GENG 230 20
The Use of EPSILON
q 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:
import math
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)
import math
EPSILON = 1E-14
r = math.sqrt(2.0)
if abs(r * r - 2.0) < EPSILON :
print("sqrt(2.0) squared is approximately 2.0")
Computer Programming - GENG 230 21
Lexicographical Order for Strings
q To compare Strings in ‘dictionary’ like order:
string1 < string2
q Notes for Lexicographical Order :
q All UPPERCASE letters come before lowercase
q ‘space’ comes before all other printable characters
q Digits (0-9) come before all letters
q See Appendix A for the Basic Latin (ASCII) Subset of Unicode
o Example1 :
if 'A'>'a' :
print(' A > a ')
else:
print(' A < a ')
#output A < a
o Example2 :
if 'a' >'9' :
print(' a > 9 ')
else:
print(' a < 9 ')
#output a > 9
Computer Programming - GENG 230 22
Operator Precedence
q The comparison operators have lower precedence than arithmetic operators
Ø Calculations are done before the comparison
floor = 1
height = 0
if floor > height + 1 :
print("Yes")
else:
print("No")
#output No
Computer Programming - GENG 230 23
Example
q 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. Write a Python program to find the discounted price if the
purchase is 140$ or 100$
originalPrice = 140
if originalPrice < 128 :
discountRate = 0.92
else :
discountRate = 0.84
discountedPrice = discountRate * originalPrice
print ("The discounted price is : " , discountedPrice)
Computer Programming - GENG 230 24
3.3 Nested Branches
Computer Programming - GENG 230 25
3.3 Nested Branches
q Nested Branches:
• Refers to the use of if statement inside another if or else statement.
time > 12
time = int(input('Enter the time as a value between 5 and 24: '))
if time > 12:
if time <= 18: True False
print('Good Afternoon')
else: time <= 18 print("Good Morning")
print('Good Evening')
else:
print("Good Morning") True False
print("Good Afternoon") print("Good Evening")
Computer Programming - GENG 230 26
3.3 Nested Branches: example
# Get the student's exam score and attendance
exam_score = float(input("Enter the student's exam score (0-100): "))
attendance = int(input("Enter the number of classes attended (0-20): ")) exam_score >= passing_score
# Define the passing criteria
passing_score = 60
required_attendance = 15 True False
# Check if the student passed Print(“Congratulations! …..”) Print(“Sorry, you
if exam_score >= passing_score: attendance >= required_attendance did …..”)
print("Congratulations! You passed the exam.")
True False
print("Your attendance print("Your attendance
# Now, check attendance is good…. ”) is low…. ”)
if attendance >= required_attendance:
print("Your attendance is good. Keep it up!")
else:
print("Your attendance is low. Attend more classes to improve.")
else:
print("Sorry, you did not pass the exam. Study harder for the next one.")
Computer Programming - GENG 230 27
3.3 Nested Branches: Tax example
Single
<= 32000
> 32000
Married
<= 64000
> 64000
Computer Programming - GENG 230 28
3.3 Nested Branches: Flowchart for the Tax
Example
Computer Programming - GENG 230 29
3.3 Nested Branches: Flowchart for the Tax Example
Computer Programming - GENG 230 30
Nested if Statement
# Nested if statement example
x = 10
y = 5
if x > 5:
if y > 3:
print("Both x and y are greater than their respective thresholds.")
else:
print("x is greater than 5, but y is not greater than 3.")
else:
print("x is not greater than 5.")
# Output:
# Both x and y are greater than their respective thresholds.
Computer Programming - GENG 230 31
3.4 Multiple Alternatives
Computer Programming - GENG 230 32
3.4 Multiple Alternatives
q The keywords of the if statement are:
• if
• elif
• else
q Once condition is true, the
corresponding statements is
executed, and the remaining
elif will not be executed.
q The final else statement will
be executed if all conditions
are false.
q The last else is optional.
Computer Programming - GENG 230 33
3.4 Multiple Alternatives: Example
q Table 4 shows the earthquake value and the effect of each value. Write a python
program that display the effect based on the entered value.
q The different conditions are as below:
Ø 8 (or greater)
Ø 7 to 7.99
Ø 6 to 6.99
Ø 4.5 to 5.99
Ø Less than 4.5
Computer Programming - GENG 230 34
3.4 Multiple Alternatives: Example flowchart
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
Damage to poorly constructed building
>= 4.5?
s
False
No destruction of buildings
Computer Programming - GENG 230 35
3.4 Multiple Alternatives: Example
q Python Code for earthquake Example:
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")
Computer Programming - GENG 230 36
3.7 Boolean Variables and
Operators
Computer Programming - GENG 230 37
3.7 Boolean Variables and Operators
q A Boolean variable is often called a flag because it can be either:
Ø True
Ø False
q Example:
isAvailable = True
q There are three Boolean Operators: and, or, not
Ø They are used to combine multiple conditions.
• Example1:
number >= 0 and number <= 40
• Example2:
if temp > 0 and temp < 100 :
print("Liquid")
Computer Programming - GENG 230 38
Combined Conditions: and
q Combining two conditions is often used in range checking
q Is a value between two other values?
q Both sides of the and must be true for the result to be true
• Example:
temp=int(input("Enter water temperature"))
if temp > 0 and temp < 100 :
print("Liquid")
else:
print("Not Liquid")
# when temp = 50 output is Liquid
# when temp = 120 output is Not Liquid
Computer Programming - GENG 230 39
Combined Conditions: or
q Combining two conditions is often used in range checking
q Is a value between two other values?
q Both sides of the and must be true for the result to be true
• Example:
temp=int(input("Enter water temperature"))
if temp <= 0 or temp >= 100 :
print("Not liquid")
q If either condition is true
Ø The result is true
Computer Programming - GENG 230 40
Combined Conditions: not
q If you need to invert a boolean variable or comparison, precede it with not
• Example1:
if not attending or grade < 60 :
print("Drop?")
• Example2:
if attending and not(grade < 60) :
print("Stay")
q If either condition is true
Ø The result is true
Computer Programming - GENG 230 41
Boolean Operator Examples
Computer Programming - GENG 230 42
Example
num1 = 5
num2 = 10
num3 = 15
num4 = 20
print( num1 == num2) #False
print( num1 <= num4) #True
print( num1 != num3) #True
print (num1 <= num2 – 5) #True
print (num1 < num2 or num1 > num4) #True
print (num1 < num2 and num1 > num4) #False
print (not (num1 < num2 or num1 > num4)) #False
Computer Programming - GENG 230 43
3.8 Analyzing Strings
Computer Programming - GENG 230 44
3.8 Analyzing Strings
q Sometimes it’s necessary to analyze or ask certain questions about a particular string.
q Sometimes it is necessary to determine if a string contains a given substring. That is,
one string contains an exact match of another string.
q Given this code segment,
name = "John Wayne "
q The code
"Way " in name
q The output for this code is True because the substring "Way " occurs within the string stored
in variable name.
q The not in operator is the inverse on the in operator
Computer Programming - GENG 230 45
Operations for Testing Substrings
Computer Programming - GENG 230 46
Operations for Testing Substrings
q Example:
# Sample input string
s = "Hello, world!"
# Check if 'Hello' is in the string
contains_hello = 'Hello' in s
# Check if 'world' is not in the string
not_contains_world = 'world' not in s
# Check if the string starts with 'He'
starts_with_he = s.startswith('He')
# Output the results
print('Hello in s: ' + str(contains_hello) )
print('world not in s:' + str(not_contains_world))
print('s starts with He' + str(starts_with_he))
Computer Programming - GENG 230 47
Operations for Testing Substrings
q Example:
# Sample input string
s = "Hello, world!"
# Check if the string ends with 'ld!'
ends_with_ld = s.endswith('ld!')
# Check if 'lo, wo' is a substring of the string
substring_lo_wo = 'lo, wo' in s
# Check if 'planet' is a substring using find (returns -1 if not found)
find_planet = s.find('planet')
# Check if 'world' is a substring using find
find_world=s.find('world')
# Output the results
print('ends with ld!: ' + str(ends_with_ld))
print('lo, wo in s : ' + str(substring_lo_wo))
print('planet in s using find: '+ str(find_planet))
print('world in s using find returns the lowest index in the string world: '+ st
r(find_world))
Computer Programming - GENG 230 48
Testing String Characteristics
Computer Programming - GENG 230 49
Testing String Characteristics
q Example:
# Sample input string
s = "Hello123"
# Check if all characters are alphanumeric
is_alphanumeric = s.isalnum()
# Check if all characters are alphabetic
is_alpha = s.isalpha()
# Check if all characters are digits
is_digit = s.isdigit()
# Output the results
print('Is alphanumeric: '+ str(is_alphanumeric))
print('Is alphabetic: ' + str(is_alpha))
print('Is digit: '+ str(is_digit))
Computer Programming - GENG 230 50
Testing String Characteristics
Computer Programming - GENG 230 51
Testing String Characteristics
q Example:
# Sample input string
s = "Hello World"
# Check if all characters are lowercase
is_lower = s.islower()
# Check if all characters are whitespace
is_space = s.isspace()
# Check if all characters are uppercase
is_upper = s.isupper()
# Output the results
print('Is lowercase: ' , is_lower)
print('Is whitespace: ' , is_space)
print('Is uppercase: ' , is_upper)
Computer Programming - GENG 230 52
Comparing and Analyzing Strings
Computer Programming - GENG 230 53
3.9 Input Validation
Computer Programming - GENG 230 54
Example
Test the program with a range of inputs including:
12, 14, 13, -1, 0, 23, 19
Computer Programming - GENG 230 55
Practice Examples
3.1 The if Statement
Computer Programming - GENG 230 56
Computer Programming - GENG 230 57
Computer Programming - GENG 230 58
Computer Programming - GENG 230 59
Computer Programming - GENG 230 60
Practice Examples
3.2 Relational Operators
Computer Programming - GENG 230 61
Computer Programming - GENG 230 62
Computer Programming - GENG 230 63
Computer Programming - GENG 230 64
Computer Programming - GENG 230 65
Practice Examples
3.3 Nested Branches
Computer Programming - GENG 230 66
Computer Programming - GENG 230 67
3000
Computer Programming - GENG 230 68
Computer Programming - GENG 230 69
Computer Programming - GENG 230 70
Practice Examples
3.4 Multiple Alternatives
Computer Programming - GENG 230 71
Computer Programming - GENG 230 72
Computer Programming - GENG 230 73
Practice Examples
3.7 Boolean Variables and
Operators
Computer Programming - GENG 230 74
Computer Programming - GENG 230 75
Computer Programming - GENG 230 76
Computer Programming - GENG 230 77
Practice Examples
3.8 Analyzing Strings
Computer Programming - GENG 230 78
Computer Programming - GENG 230 79
Computer Programming - GENG 230
Computer Programming - GENG 230
Computer Programming - GENG 230
Computer Programming - GENG 230