Sometimes, you want your program to do something different based on different conditions. These are called conditional statements.
For example, consider the pay calculator. If this employer offers 50% extra pay for overtime (i.e., worked > 40 hours), how could we account for that?
wage = float(input("Enter your hourly wage: "))
hours = float(input("Enter your number of hours worked: "))
#option 1: only correct if they didn't work overtime
pay = wage*hours
#option 2: only correct if they worked overtime
#overtime_hours = hours-40
#pay = (wage*40) + (wage*1.5*overtime_hours)
print("Total pay: ",pay)
if statements¶if:total_bill = 35.63
age = float(input("What is your age? "))
if age > 65:
print("Applying 10% senior discount")
total_bill = total_bill * 0.9
#any indented code is only runs
#when the condition is True
#un-indented code runs no matter what
print("Your total bill is", total_bill)
if-else statements¶if:else:height = int(input("Enter your height in inches: "))
if height < 60:
print("You are not tall enough for this ride.")
else:
print("You are tall enough for this ride.")
How could we make this work using an if-else?
wage = float(input("Enter your hourly wage: "))
hours = float(input("Enter your number of hours worked: "))
#option 1: only correct if they didn't work overtime
pay = wage*hours
#option 2: only correct if they worked overtime
#overtime_hours = hours-40
#pay = (wage*40) + (wage*1.5*overtime_hours)
print("Total pay: ",pay)
The Boolean type has two possible values: True and False
bool_variable = True
if bool_variable:
print("The condition it True!")
The condition for an if/if-else statement can be anything that results in a Boolean. An expression, like height < 60 that results in a Boolean is called a Boolean expression.
< less than> greater than<= less than or equal>= greater than or equal== equal (comparison)= is used for assignment, they're different operators, don't confuse them!!= not equalsecret_number = 7
guess = int(input("Guess a number: "))
if guess == secret_number:
print("That was right, good guess!")
else:
print("Wrong!")
total_bill = 121.50
party_size = int(input("Enter number of people at the table: "))
non_profit = input("Was this a business lunch for a non-profit organization? ")
if non_profit != "yes":
print("Calculating 6% sales tax.")
total_bill = total_bill * 1.06
if party_size >= 8:
print("Automatically adding 15% gratuity.")
total_bill = total_bill * 1.15
print("Your total is",total_bill)