Slide 1
Decision Structures
Joan Boone
jpboone@email.unc.edu
Summer 2020
Decision Structures Joan Boone jpboone@email.unc.edu Summer 2020 - - PowerPoint PPT Presentation
INLS 560 Programming for Information Professionals Decision Structures Joan Boone jpboone@email.unc.edu Summer 2020 Slide 1 Topics Part 1 if and if-else statements Part 2 Nested Decision Structures with if-else if-elif-else
Slide 1
Joan Boone
jpboone@email.unc.edu
Summer 2020
Slide 2
Slide 3
Slide 4
executes statements
statement are executed one after another, in the same order they appear in your program
control the flow of execution
– Decision structures choose among several possible actions; also
called conditional or branching structures
– Repetition structures repeat an action until some stop condition is
met; also called iteration or loop structures “Would you tell me, please, which way I ought to go from here?” “That depends a good deal on where you want to get to,” said the Cat.
Slide 5
sales > 50000
True False
bonus = 500.00 commission = 0.12 print(“You met your quota!”)
if sales > 50000: bonus = 500.00 commission = 0.12 print(“You met your quota!”)
if condition: statement statement etc.
Slide 6
True or False
determine whether a specific relationship exists between two values
Operator Expression Meaning > x > y Is x greater than y? < x < y Is x less than y? >= x >= y Is x greater than or equal to y? <= x <= y Is x less than or equal to y? == x == y Is x equal to y? != x != y Is x not equal to y?
Slide 7
Gross pay calculation for regular (vs. overtime) hours
hours_worked = float(input('Enter hours worked: ')) if hours_worked <= 40: gross_pay = hours_worked * 15.50 print('Gross pay:', gross_pay)
Sales price calculation where discounts only apply to $10+ items
if original_price > 10.00: sale_price = original_price - (original_price * 0.2) total_price = sale_price * 1.0475 print('Total price is', total_price)
Time conversion only applies to a positive number of seconds
total_seconds = int(input('Enter number of seconds: ')) if total_seconds > 0: hours = total_seconds // 3600 remaining_seconds = total_seconds % 3600 minutes = remaining_seconds // 60 remaining_seconds = remaining_seconds % 60 print('Hours:', hours, '\tMinutes:', minutes, '\tSeconds:', remaining_seconds)
Slide 8
temp < 40
False True
print(“Nice weather we're having.”)
if temp < 40: print(“A little cold, isn't it?”) else: print(“Nice weather we're having”)
if condition: statement statement etc. else: statement statement etc.
print(“A little cold, isn't it?”)
Slide 9
# Simple payroll program to calculate gross pay, # including overtime wages base_hours = 40 # Base hours per week
hours = float(input('Enter the number of hours worked: ')) pay_rate = float(input('Enter the hourly pay rate: ')) if hours > base_hours: # Overtime hours
gross_pay = base_hours * pay_rate + overtime_pay else: # Regular hours gross_pay = hours * pay_rate print('The gross pay is', gross_pay)
Source: Starting Out with Python by Tony Gaddis gross_pay_with_ot.py
Slide 10
password = input('Enter a password:') if password == 'somethingcryptic': print('Password accepted.') else: print('Sorry, that is the wrong password')
Source: Starting Out with Python by Tony Gaddis password_test.py
Slide 11
Slide 12
years_on_job >= 2
True False
print(“Not enough years to qualify.”)
False True
salary >= 30K print(“You qualify for the loan.”) print(“Salary does not meet loan qualifications.”)
Get customer's annual salary Get number of years on current job If customer earns minimum salary If years on the job meets minimum Customer qualifies for loan Else Notify customer: too few years on job Else Notify customer: salary is too low
Flowchart Pseudocode
Slide 13
# This program determines whether a customer qualifies for a loan min_salary = 30000.0 min_years = 2 salary = float(input("Enter your annual salary: ")) years_on_job = int(input("Enter number of years employed: ")) if salary >= min_salary: 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 $',min_salary, ' per year to qualify.', sep='') print('Loan qualification completed.') loan_qualification.py
Slide 14
85.0 degrees Fahrenheit is 29.44 degrees Celsius
Pseudocode
Slide 15
# Convert a temperature value from Fahrenheit to Celsius, or vice versa temp = float(input('Enter a temperature value: ')) conversion = input('Enter type of conversion (f2c or c2f): ') if conversion == 'f2c': converted_temp = (temp - 32) * 5.0 / 9 print(temp, 'degrees Fahrenheit is ', format(converted_temp, '.2f'), ' degrees Celsius') else: converted_temp = (temp * 9 / 5.0) + 32 print(temp, 'degrees Celsius is ', format(converted_temp, '.2f'), ' degrees Fahrenheit') temp_conversion_v1.py
Slide 16
numeric before trying to convert it?
– temp is a string variable with the value the user entered
– Returns True if all characters in the string are numeric (0-9) – Returns False if the string variable contains any characters
that are not numeric
temp = input('Enter a temperature value: ') if temp.isnumeric(): temp = float(temp) conversion = input('Enter type of conversion (f2c or c2f): ') # Code to convert the temp goes here else: print(temp, "is not a valid temperature value")
Slide 17
# Convert temperature value from Fahrenheit to Celsius, or vice versa temp = input('Enter a temperature value: ') if temp.isnumeric(): temp = float(temp) conversion = input('Enter type of conversion (f2c or c2f): ') if conversion == 'f2c': converted_temp = (temp - 32) * 5.0 / 9 print(temp, 'degrees Fahrenheit is ', format(converted_temp, '.2f'), ' degrees Celsius') else: converted_temp = (temp * 9 / 5.0) + 32 print(temp, 'degrees Celsius is ', format(converted_temp, '.2f'), ' degrees Fahrenheit') else: print(temp, "is not a valid temperature value") Same code as in temp_conversion_v1.py temp_conversion_v2.py
Slide 18
temp = input('Enter a temperature value: ') if temp.isnumeric(): temp = float(temp) conversion = input('Enter type of conversion (f2c or c2f): ') if conversion == 'f2c': converted_temp = (temp - 32) * 5.0 / 9 print(temp, 'degrees Fahrenheit is ', format(converted_temp, '.2f'), ' degrees Celsius') else: if conversion == 'c2f': converted_temp = (temp * 9 / 5.0) + 32 print(temp, 'degrees Celsius is ', format(converted_temp, '.2f'), ' degrees Fahrenheit') else: print(conversion, 'is not a valid conversion type') else: print(temp, "is not a valid temperature value")
Suppose you also want to validate the conversion type: did the user enter f2c or c2f? Add the new if-else statement (in the blue box) to temp_conversion_v2 and test your program
Slide 19
temp = input('Enter a temperature value: ') if temp.isnumeric(): temp = float(temp) conversion = input('Enter type of conversion (f2c, c2f, k2f, f2k, k2c, or c2k): ') if conversion == 'f2c': # Fahrenheit to Celsius converted_temp = (temp - 32) * 5.0 / 9 print(temp, 'degrees Fahrenheit is ', format(converted_temp, '.2f'), ' degrees Celsius') else: if conversion == 'c2f': # Celsius to Fahrenheit converted_temp = (temp * 9 / 5.0) + 32 print(temp, 'degrees Celsius is ', format(converted_temp, '.2f'), ' degrees Fahrenheit') else: if conversion == 'k2f': # Kelvin to Fahrenheit converted_temp = (temp - 273.15) * 1.8 + 32 print(temp, 'degrees Kelvin is ', format(converted_temp, '.2f'), ' degrees Fahrenheit') else: if conversion == 'f2k': # Fahrenheit to Kelvin converted_temp = (temp - 32)*5/9 + 273.15 print(temp, 'degrees Fahrenheit is ', format(converted_temp, '.2f'), ' degrees Kelvin') else: if conversion == 'k2c': # Kelvin to Celsius converted_temp = temp - 273.15 print(temp, 'degrees Kelvin is ', format(converted_temp, '.2f'), ' degrees Celsius') else: if conversion == 'c2k': # Celsius to Kelvin converted_temp = temp + 273.15 print(temp,'degrees Celsius is ',format(converted_temp, '.2f'),' degrees Kelvin') else: print(conversion, 'is not a valid conversion type') else: print(temp, "is not a valid temperature value")
6 possible conversion types: f2c, c2f, k2f, f2k, k2c, or c2k
Slide 20
temp = input('Enter a temperature value: ') if temp.isnumeric(): temp = float(temp) conversion = input('Enter type of conversion (f2c, c2f, k2f, f2k, k2c, or c2k): ') if conversion == 'f2c': # Fahrenheit to Celsius converted_temp = (temp - 32) * 5.0 / 9 print(temp, 'degrees Fahrenheit is ', format(converted_temp, '.2f'), ' degrees Celsius') elif conversion == 'c2f': # Celsius to Fahrenheit converted_temp = (temp * 9 / 5.0) + 32 print(temp, 'degrees Celsius is ', format(converted_temp, '.2f'), ' degrees Fahrenheit') elif conversion == 'k2f': # Kelvin to Fahrenheit converted_temp = (temp - 273.15) * 1.8 + 32 print(temp, 'degrees Kelvin is ', format(converted_temp, '.2f'), ' degrees Fahrenheit') elif conversion == 'f2k': # Fahrenheit to Kelvin converted_temp = (temp - 32)*5/9 + 273.15 print(temp, 'degrees Fahrenheit is ', format(converted_temp, '.2f'), ' degrees Kelvin') elif conversion == 'k2c': # Kelvin to Celsius converted_temp = temp - 273.15 print(temp, 'degrees Kelvin is ', format(converted_temp, '.2f'), ' degrees Celsius') elif conversion == 'c2k': # Celsius to Kelvin converted_temp = temp + 273.15 print(temp, 'degrees Celsius is ', format(converted_temp, '.2f'), ' degrees Kelvin') else: print(conversion, 'is not a valid conversion type') else: print(temp, "is not a valid temperature value")
Slide 21
# Determine the ticket price for a given seat location. # Valid values are suite, box, orchestra, mezzanine, and balcony. location = input('Enter seat location: ') price = 0.0 if location == 'suite': price = 100.00 else: if location == 'box': price = 75.00 else: if location == 'orchestra': price = 50.00 else: if location == 'mezzanine': price = 40.00 else: if location == 'balcony': price = 30.00 else: print('Enter a valid seat location') if price > 0: print('Your ticket price is', price) seat_location_nestedif.py
Slide 22
if location == 'suite': price = 100.00 elif location == 'box': price = 75.00 elif location == 'orchestra': price = 50.00 elif location == 'mezzanine': price = 40.00 elif location == 'balcony': price = 30.00 else: print('Enter a valid seat location')
seat_location_if_elif.py
Slide 23
represent any decision structure
variable (e.g., seat location, temp conversion type)
– Use of if-elif may avoid deeply nested indentation – Code may be easier to understand than nested if-else's
nested if-else statement
as if-elif. For example, recall the loan qualification program where we were checking for the salary and years on the job – these are different variables, so using if-elif is not a good choice
Slide 24
Slide 25
be true
Usage example: Google Advanced Search Expression Meaning (x > y) and (a < b) Is x greater than y AND is a less than b? (x == y) or (x == z) Is x equal to y OR is x equal to z? not (x > y) Is the expression x > y NOT true?
Slide 26
Pseudocode examples:
If (userid is valid) and (password is valid) Log user into app If (bank balance > loan amount) or (credit is good) Loan the money If not ( (engine starts) and (weather is good) ) Notify passengers, schedule service, check forecast Else go flying! Value of x Value of y
x and y x or y not(x)
true true true true false true false false true false false true false true true false false false false true
Slide 27
salary = float(input("Enter your annual salary: ")) years_on_job = int(input("Enter number of years employed: "))
Original version
if salary >= min_salary: 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 $',min_salary, ' per year to qualify.', sep='')
Revised version
if salary >= min_salary and years_on_job >= min_years: print('You qualify for the loan.') else: print('You do not qualify for the loan')
Slide 28
To check the value of a Boolean variable:
if today_is_Thursday: print('Then it must be Thursday')
if today_is_Thursday == True: print('Then it must be Thursday') Note: checking equality with == is not necessary, and a little redundant
Slide 29
if salary >= min_salary: customer_meets_salary_requirement = True else: customer_meets_salary_requirement = False if years_on_job >= min_years: customer_meets_years_on_job_requirement = True else: customer_meets_years_on_job_requirement = False
Boolean variables may make your code a little verbose, but they can also make your code easier to read and understand.
if customer_meets_salary_requirement and customer_meets_years_on_job_requirement: print('You qualify for the loan.') else: print('You do not qualify for the loan')
Slide 30
Slide 31
loan_qualification_v2.py
min_salary = 30000.0 min_years = 2 salary = input("Enter your annual salary: ") if salary.isnumeric(): salary = float(salary) years_on_job = input("Enter number of years employed: ") if years_on_job.isnumeric(): years_on_job = int(years_on_job) if salary >= min_salary: 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 $', min_salary, ' per year to qualify.', sep='') else: print(years_on_job, "is not a valid value for years employed") else: print(salary, "is not a valid value for salary" ) print('Loan qualification completed.')