Decision Structures Joan Boone jpboone@email.unc.edu Summer 2020 - - PowerPoint PPT Presentation

decision structures
SMART_READER_LITE
LIVE PREVIEW

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
SLIDE 1

Slide 1

Decision Structures

Joan Boone

jpboone@email.unc.edu

Summer 2020

INLS 560

Programming for Information Professionals

slide-2
SLIDE 2

Slide 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-3
SLIDE 3

Slide 3

Topics

Part 1

  • if and if-else statements
slide-4
SLIDE 4

Slide 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-5
SLIDE 5

Slide 5

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-6
SLIDE 6

Slide 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-7
SLIDE 7

Slide 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

  • riginal_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-8
SLIDE 8

Slide 8

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-9
SLIDE 9

Slide 9

if-else Example

# Simple payroll program to calculate gross pay, # including overtime wages base_hours = 40 # Base hours per week

  • t_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

  • vertime_hours = hours - base_hours
  • vertime_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-10
SLIDE 10

Slide 10

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,

  • r in other words, are the string variables equal?
slide-11
SLIDE 11

Slide 11

Topics

Part 2

  • Nested Decision Structures with if-else
  • if-elif-else statement
slide-12
SLIDE 12

Slide 12

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-13
SLIDE 13

Slide 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-14
SLIDE 14

Slide 14

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-15
SLIDE 15

Slide 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-16
SLIDE 16

Slide 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-17
SLIDE 17

Slide 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 temp_conversion_v2.py

slide-18
SLIDE 18

Slide 18

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-19
SLIDE 19

Slide 19

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

slide-20
SLIDE 20

Slide 20

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-21
SLIDE 21

Slide 21

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-22
SLIDE 22

Slide 22

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

slide-23
SLIDE 23

Slide 23

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

slide-24
SLIDE 24

Slide 24

Topics

Part 3

  • Logical operators: and, or, not
  • Boolean variables
slide-25
SLIDE 25

Slide 25

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
  • r
  • 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?

slide-26
SLIDE 26

Slide 26

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 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
SLIDE 27

Slide 27

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')

slide-28
SLIDE 28

Slide 28

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

slide-29
SLIDE 29

Slide 29

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')

slide-30
SLIDE 30

Slide 30

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

slide-31
SLIDE 31

Slide 31

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.')