Making Decisions With Code: If Statements
Making Decisions With Code: If Statements
if statements
answer=input("Would you like express shipping?")
if answer == "yes" :
print("That will be an extra $10")
== is equal to if answer == "yes" :
!= is not equal to if answer != "no" :
< is less than if total < 100 :
> is greater than if total > 100 :
<= is less than or equal to if total <= 100 :
>= is greater than or equal to if total >= 100 :
If statements allow you to specify code that only
executes if a specific condition is true
answer=input("Would you like express shipping? ")
if answer == "yes" :
print("That will be an extra $10")
print("Have a nice day")
if answer == "yes" :
if not answer == "no" :
deposit = 150
if deposit > 100 :
print("You get a free toaster!")
print("Have a nice day")
Branching
What if you get a free toaster for over $100 and a
free mug for under $100
#if the variable freeToaster is True
#the print statement will execute
if freeToaster :
print("enjoy your toaster")
Make sure you test what happens when your if statement
is true and what happens when your if statement is false.
DEMO
Using a Boolean variable and testing all paths
Why does our code crash when we enter a value of
50 for a deposit?
deposit= input("how much would you like to deposit? ")
if float(deposit) > 100 :
#Set the boolean variable freeToaster to True
freeToaster=True
#if the variable freeToaster is True
#the print statement will execute
if freeToaster :
print("enjoy your toaster")
Look at the error message: Name ‘freeToaster’ is not defined.
It’s always a good idea to initialize your variables!
#Initialize the variable to fix the error
freeToaster=False
deposit= input("how much would you like to deposit? ")
if float(deposit) > 100 :
#Set the boolean variable freeToaster to True
freeToaster=True
#if the variable freeToaster is True
#the print statement will execute
if freeToaster :
print("enjoy your toaster")
Aren’t you just making the code more complicated by
using the Boolean variable?
• That depends…
• What if you are writing a program, and there is more than one
place you have to check that condition? You could check the
condition once and remember the result in the Boolean variable
• What if the condition is very complicated to figure out? It might
be easier to read your code if you just use a Boolean variable
(often called a flag) in your if statement
And now we have more ways to make typing
mistakes! Can you find three?
deposit=input("How much would you like to deposit? ")
if float(deposit) > 100
print("You get a free toaster!")
freeToaster=true
else:
print("Enjoy your mug!")
print("Have a nice day")