Decision-Structures

pdf

School

Davidson County Community College *

*We aren’t endorsed by this school

Course

110

Subject

Computer Science

Date

Feb 20, 2024

Type

pdf

Pages

30

Uploaded by MinisterHeatOstrich21

Report
Slide 1 Decision Structures Joan Boone jpboone@email.unc.edu INLS 560 Programming for Information Science
Slide 2 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 3 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
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 4 if Statement 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. General format: Python example:
Slide 5 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 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)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 7 if-else Statement 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. General format: Python example: print(“A little cold, isn't it?”)
Slide 8 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) Source: Starting Out with Python by Tony Gaddis gross_pay_with_ot.py
Slide 9 Using if-else to Compare Strings # 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' ) Source: Starting Out with Python by Tony Gaddis password_test.py Checking to see if 2 string variables have the same value, or in other words, are the string variables equal?
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 10 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 11 When there are multiple conditions to check: use Nested Decision Structures 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 12 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
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 13 Using if-else for Temperature Conversion 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 Pseudocode
Slide 14 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 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" )
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 16 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 temp_conversion_v2.py
Slide 17 Exercise: Temperature Conversion v3 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 18 What if the temperature conversion program needed to handle Kelvin temperatures, too? 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
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 19 if-elif-else statement Alternative decision structure that can sometimes be used instead of nested if-else statements 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 20 Another nested if-else example. What is the ticket price for each seat location? # 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 21 if-elif-else example What is the ticket price for each seat location? 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
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 22 When to use: nested if-else vs. if-elif if-else is generally used most often because it can represent any decision structure if-elif is typically used when testing the value of a single 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 if-elif is never required: it can always be re-written as a nested if-else statement But , a nested if-else statement cannot always be re-written 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
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 23 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
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 24 When one Boolean expression is not enough... Logical Operators and Connects two Boolean expressions into one compound expression Both sub-expressions must be true for the compound expression to be true or Connects two Boolean expressions into one compound expression One or both sub-expressions must be true for the compound expression to be true not Reverses the Boolean value of its operand 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?
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 25 Truth Tables for Logical Operators 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 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
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 26 Loan Qualifier Program, revised, to use a Logical Operator 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' )
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 27 Boolean Variables Data types so far: int , float , and str (string) bool data type allows you to create Boolean variables that have the values True or False Example: today_is_Thursday = True To check the value of a Boolean variable: if today_is_Thursday: print('Then it must be Thursday') This is the same as: if today_is_Thursday == True: print('Then it must be Thursday') Note: checking equality with == is not necessary, and a little redundant
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 28 Loan Qualifier with Boolean Variables 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')
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 29 Summary: Why Use Decision Structures? All programs solve some type of problem that requires data – that data may be provided by a user and/or generated by your program. When you design a program, you have to decide what data you need to solve the problem, and what conditions that data must satisfy. Decision structures, i.e., if-else and if-elif statements, provide the mechanism for specifying the conditions that must be met. Conditions are often specified to validate input data and to process data
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Slide 30 Summary: Using Decision Structures 4 conditions 4 if-else statements 2 conditions to validate input 2 conditions to process input 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.' )
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help