decision structures
play

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


  1. INLS 560 Programming for Information Professionals Decision Structures Joan Boone jpboone@email.unc.edu Summer 2020 Slide 1

  2. Topics Part 1 ● if and if-else statements Part 2 ● Nested Decision Structures with if-else ● if-elif-else statement Part 3 ● Logical operators ● Boolean variables Slide 2

  3. Topics Part 1 ● if and if-else statements Slide 3

  4. Flow of Control ● Flow of control is the order that a program performs actions, or executes statements ● By default, statements are executed in sequential order, i.e., statement are executed one after another, in the same order they appear in your program ● Most programming languages use 2 kinds of structures to 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. --- Lewis Carroll, Alice in Wonderland Slide 4

  5. if Statement General format: if condition : statement True sales > 50000 statement etc. bonus = 500.00 False Python example: if sales > 50000: commission = 0.12 bonus = 500.00 commission = 0.12 print(“You met your quota!”) print(“You met your quota!”) Slide 5

  6. Specify if conditions using Boolean Expressions and Relational Operators ● A boolean expression is one that results in a value of True or False ● Typically, they are formed with relational operators that 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 6

  7. if Statement Examples 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 original_price = float(input("Enter the item's original price: ")) 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 7

  8. if-else Statement General format: if condition : True False statement temp < 40 statement etc. else: print(“A little cold, print(“Nice weather statement isn't it?”) we're having.”) statement etc. Python example: if temp < 40: print(“A little cold, isn't it?”) else: print(“Nice weather we're having”) Slide 8

  9. if-else Example # Simple payroll program to calculate gross pay, # including overtime wages base_hours = 40 # Base hours per week ot_multiplier = 1.5 # Overtime multiplier hours = float(input('Enter the number of hours worked: ')) pay_rate = float(input('Enter the hourly pay rate: ')) if hours > base_hours: # Overtime hours overtime_hours = hours - base_hours overtime_pay = overtime_hours * pay_rate * ot_multiplier gross_pay = base_hours * pay_rate + overtime_pay else: # Regular hours gross_pay = hours * pay_rate print('The gross pay is', gross_pay) gross_pay_with_ot.py Source: Starting Out with Python by Tony Gaddis Slide 9

  10. Using if-else to Compare Strings Checking to see if 2 string variables have the same value, or in other words, are the string variables equal? # Compare 2 strings with the == operator password = input('Enter a password:') if password == 'somethingcryptic': print('Password accepted.') else: print('Sorry, that is the wrong password') password_test.py Source: Starting Out with Python by Tony Gaddis Slide 10

  11. Topics Part 2 ● Nested Decision Structures with if-else ● if-elif-else statement Slide 11

  12. When there are multiple conditions to check: use Nested Decision Structures Flowchart Pseudocode Get customer's annual salary False True Get number of years on current job salary >= 30K 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 print(“Salary does False True not meet loan years_on_job qualifications.”) >= 2 print(“Not enough print(“You qualify years to qualify.”) for the loan.”) Slide 12

  13. Nested Decision Structures Example # 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 13

  14. Using if-else for Temperature Conversion Pseudocode Prompt user for temperature value and convert to float Prompt user for type of conversion: f2c or c2f If type of conversion is Fahrenheit to Celsius ( f2c ) Converted temperature value = (temp - 32) * 5.0 / 9 Else ( c2f ) Converted temperature value = (temp * 9 / 5.0) + 32 Print converted temperature value, e.g. 85.0 degrees Fahrenheit is 29.44 degrees Celsius Slide 14

  15. Using if-else for Temperature Conversion # 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 15

  16. Temperature Conversion with nested decision structures ● Suppose you want to ensure that the temperature value is numeric before trying to convert it? ● You can use the Python string function: temp.isnumeric() – 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 16

  17. Temperature Conversion v2: using nested if-else to test 2 conditions # 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 Slide 17 temp_conversion_v2.py

  18. Exercise: Temperature Conversion v3 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 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" ) Slide 18

Recommend


More recommend