4. If/Else Decision Structure
◦ All previous instructions have been consecutively executed
One
After
The
Other
◦ If/Else checks a Boolean condition then makes a decision
◦ If condition is
◦ True: one set of instructions are executed
◦ False: a different set of instructions is executed
5. The if Statement
◦ All previous instructions have been consecutively
executed
One
After
The
Other
◦ If statement makes a decision
◦ If a Boolean expression or condition is
◦ True: one set of instructions are executed
◦ False: a different set of instructions is executed
6. Python Structures
◦ Control structure: logical design that controls the
order of how a set of Python statements execute
◦ Sequence structure: set of statements that execute in the
order they appear
◦ Decision structure: specific action(s) performed only if a
condition exists
◦ Also known as a selection structure
7. The if Statement Flowchart
◦ Diamond represents true/false condition that must be
tested
◦ Actions can be conditionally executed
◦ Performed only when a condition is true
◦ Single alternative decision structure: provides only
one alternative path of execution
◦ If condition is not true, exit the structure
8. The if Statement Flowchart
◦ Single alternative decision structure
◦ Provides only one alternative path of execution
◦ If condition is not true, exit the structure
9. The if Statement Syntax
◦ Python syntax:
if condition:
Statement
Statement
◦ if statement
◦ Includes the keyword if followed by a Boolean condition
◦ The condition can be true or false
◦ Condition has to be followed by a colon like above
◦ When the if statement executes, the condition is tested
◦ If it is true the subsequent indented statements (called block
statements) are executed
◦ Indentation is required to tell Python when the block is finished
◦ Otherwise, block statements are skipped
10. Relational Operators
Used to compare values
and determine whether
relationships exist
◦ Greater than
◦ Less than
◦ Equal to
Compare two values and
determine how they relate
to each other
Operator Meaning
= = Equal to
! = Not equal to
> Greater than
> = Greater than or
equal to
< Less than
< = Less than or
equal to
11. Boolean Expressions
◦ Boolean expression: an expression tested by the if
statement to determine if it is true or false
◦ Example: a > b
◦ True if a is greater than b; False otherwise
◦ > is the relationship
◦ a > b is an expression
12. Boolean Expressions
• == operator determines whether the two operands are equal to one
another
• Do not confuse with assignment operator (=)
13. Boolean Expression in Flow
Chart
◦ Using a Boolean expression with the > relational
operator
14. Example
◦ Science teacher gives three tests
◦ Wants to write a program that averages test scores
◦ Wants to congratulate students if average is great
than 95
15. Example Pseudocode/Algorithm
◦ Get the first test score
◦ Get the second test score
◦ Get the third test score
◦ Calculate the average
◦ Display the average
◦ If average is > 95
◦ Congratulate the user
16. Program
# This program gets three test scores and displays their average.
# It congratulates the user if the average is a high score.
HIGH_SCORE = 95
# Get the three test scores.
test1 = int(input('Enter the score for test 1: ')) # notice that answer is
test2 = int(input('Enter the score for test 2: ')) # converted to integer
test3 = int(input('Enter the score for test 3: '))
# Calculate the average test score.
average = (test1 + test2 + test3) / 3
# Print the average
print('The average score is', average)
# If the average is a high score, congratulate the user.
if average >= HIGH_SCORE: # notice : at end of if statement
print('Congratulations!') # notice indentation
print('That is a great average!') # same indentation and end of block
17. The if-else Statement
◦ Dual alternative decision structure: two possible paths
of execution
– One is taken if the condition is true, and the other if the
condition is false
◦ Syntax: if condition:
statements
else:
other statements
◦ if clause and else clause must be aligned
◦ Statements must be consistently indented
20. Example
◦ Auto repair business wants a payroll program to pay
overtime when an employee works > 40 hours
◦ Pseudocode/algorithm
Get the number of hours worked
Get the hourly pay rate
If employee worked more than 40 hours
Calculate and display pay with overtime
Else
Calculate and display pay as usual
21. Program
# Variables to represent the base hours and the overtime multiplier.
base_hours = 40 # Base hours per week
ot_multiplier = 1.5 # Overtime multiplier
# Get the hours worked and the hourly pay rate.
hours = float(input('Enter the number of hours worked: '))
pay_rate = float(input('Enter the hourly pay rate: ')) # convert to float
# Calculate and display the gross pay.
if hours > base_hours:
overtime_hours = hours - base_hours
overtime_pay = overtime_hours * pay_rate * ot_multiplier
gross_pay = base_hours * pay_rate + overtime_pay
else:
gross_pay = hours * pay_rate
# Display the gross pay.
print('The gross pay is $', format(gross_pay, ',.2f'), sep='')
22. Comparing Strings
◦ Strings can be compared using the == and !=
operators
◦ String comparisons are case sensitive
◦ Strings can be compared using >, <, >=, and <=
◦ Compared character by character based on the ASCII values
for each character
◦ If shorter word is substring of longer word, longer word is
greater than shorter word
23. Example
name1 = 'Mary'
name2 = 'Mark'
if name1 > name2:
print(name1, ">", name2)
else:
print(name2, '>', name1)
Output
Mary > Mark
25. Example
# This program compares two strings.
# Get a password from the user.
password = input('Enter the password: ')
# Determine whether the correct password
# was entered.
if password == 'prospero':
print('Password accepted.')
else:
print('Sorry, that is the wrong password.')
26. Nested if-else Statement
◦ Sometimes a decision needs to be made after a
previous decision was made
◦ Called nesting
◦ Commonly needed in programs
◦ Example:
◦ Determine if someone qualifies for a loan, they must meet two
conditions:
◦ Must earn at least $30,000/year
◦ Must have been employed for at least two years
◦ Check first condition, and if it is true, check second condition
28. Program
# This program determines whether a bank customer qualifies for a loan.
MIN_SALARY = 30000.0 # The minimum annual salary
MIN_YEARS = 2 # The minimum years on the job
salary = float(input('Enter your annual salary: '))
years_on_job = int(input('Enter the number of ' + 'years employed: '))
if salary >= MIN_SALARY: # Determine whether the customer qualifies.
if years_on_job >= MIN_YEARS:
print('You qualify for the loan.')
else:
print('You must have been employed',
'for at least', MIN_YEARS, 'years to qualify.')
else:
print('You must earn at least $',
format(MIN_SALARY, ',.2f'), ' per year to qualify.', sep='')
29. Nested if-else Statement
Indentation
◦ Important to use proper indentation in a nested
decision structure
◦ Important for Python interpreter
◦ Will complain about indentation
◦ Makes code more readable for programmer
◦ Rules for writing nested if statements
◦ else clause should align with matching if clause
◦ Statements in each block must be consistently indented
30. The if-elif-else Statement
◦ Special version of a decision structure
◦ Uses elif instead of multiple nested elses
◦ Makes logic of nested decision structures simpler to write
◦ Can include multiple elif statements
◦ Syntax:
if condition_1:
statement(s)
elif condition_2:
statement(s)
elif condition_3:
statement(s)
else
statement(s)
Insert as many elif clauses
as necessary.
31.
32. Program
grade = int(input("what is the grade?"))
if grade >= 90:
print("you get an A")
elif grade >= 80:
print("you get a B")
elif grade >= 70:
print("you get a C")
elif grade >= 60:
print("you get a D")
else:
print("you get a F")
33. The if-elif-else Statement
◦ Alignment used with if-elif-else statement:
◦ if, elif, and else clauses are all aligned
◦ Conditionally executed blocks are consistently indented
◦ if-elif-else statement is never required, but logic
easier to follow
◦ Can be accomplished by nested if-else
◦ Code can become complex, and indentation can cause problematic long
lines