Chapter 5 – If statements
- programming involves examining a set of conditions and deciding which action to take based on those conditions
- Python’s if statement allows you tot examine the current state of a program and respond appropriately to that state
A simple example
- imagine a list of cars and you want to print the name of each car in title case, however, ‘bmw’ should be all upper case
cars.py
cars = [‘audi, ‘bmw’, subaru’, ‘toyota’]
for car in cars:
….if car == ‘bmw’:
……..print(car.upper())
….else:
….print(car.title())
Audi
BMW
Subaru
Toyota
Conditional tests
- heart of every if statement is an expression that can be evaluated as true or false to decide whether the code in an if statement should be executed
- if a conditional test is true, Python executes the code following the if statement
- if false, Python ignores the code
Checking for equality
- most conditional tests compare the current value of a variable to a specific value of interest
>>> car = ‘bmw’
>>> car == ‘bmw’
True
- equality operator – the double equal sign (==) returns true if the values match, and false if they do not
>>> car = ‘audi’
>>> car == ‘bmw’
False
- single equal sign is a statement, “set the value of car equal to audi” instead of a double equal sign which asks, “is the value of car equal to bmw?”
Ignoring case when checking for equality
- testing for equality is case-sensitive in Python
>>> car = ‘Audi’
>>> car == ‘audi’
False
- you’ll need to convert the value to lowercase if case is not important
>>> car = ‘Audi’
>>> car.lower() == ‘audi’
True
- a website that stores usernames would convert to lowercase, so ‘John’ will be rejected if any variation of ‘john’ is already in use
Checking for inequality
- inequality operator (!=) – used to determine whether two values are not equal
toppings.py
requested_topping = ‘mushrooms’
if requested_topping != ‘anchovies’:
….print(“Hold the anchovies!”)
Hold the anchovies!
- most of the conditional expressions you write will test for equality, sometimes you’ll need to test for inequality
Numerical comparisons
- testing numerical values is straight forward
>>> age = 18
>>> age == 18
True
- can test if two numbers are not equal
magic_numbers.py
answer = 17
if answer != 42:
….print(“That is not the correct answer. Please try again!”)
- conditional test passes because the value of answer (17) is not equal to 42, code is executed
That is not the correct answer. Please try again!
- can include various mathematical comparisons in your conditional statements, such as less than, less than or equal to, greater than, and greater than or equal to
>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False
- mathematical comparisons can be used in if statements
Checking multiple conditions
- sometimes you might need two conditions to be true to take action, other times just one condition
- keywords and and or can help you
Using and to check multiple conditions
- for example, check if two people are both over 21
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21
False
>>> age_1 = 22
>>> age_0 >= 21 and age_1 >= 21
True
- can also use parentheses around ages to improve readability but not required
Using or to check multiple conditions
- or expressions pass when either or both individual tests pass and fails when both individual tests fail
- for example, looking for only one person to be over 21
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 or age_1 >= 21
True
>>> age_0 = 18
>>> age_0 >= 21 or age_1 >= 21
False
Checking whether a value is in a list
- sometimes you want to check if a list contains a certain value before taking an action
- for example, if a new username already exists in a list of current usernames before completing someone’s registration on a website
- in – used to find out whether a particular value is already in a list
- for example, checking if a list of toppings a customer has requested for a pizza is in a list
>>> requested_toppings = [‘mushrooms’, ‘onions’, ‘pineapple’]
>>> ‘mushrooms’ in requested_toppings
True
>>> ‘pepperoni’ in requested_toppings
False
Checking whether a value is not in a list
- not – used check if a value does not appear in a list
- for example, checking if a user is banned before allowing them to submit a comment
banned_users.py
banned_users = [‘andrew’, ‘carolina’, ‘david’]
user = ‘marie’
if user not in banned_users:
….print(f”{user.title()}, you can post a response if you wish.”)
- marie is not in the list so she sees a message inviting her to post a response
Marie, you can post a response if you wish.
Boolean expressions
- boolean expression – conditional test
- boolean value – true or false
- boolean values are used to keep track of certain conditions, such as whether a game is running or whether a user can edit certain content on a website
game_active = True
can_edit = False
- boolean values provide an efficient way to track the state of a program or a particular condition that is important to your program
if statements
- when you understand contiional tests, you can start writing if statements
- there are several different kinds of if statements
- your choice depends on the number of conditions you need to test
Simple if statements
- simplest has one test and action
if conditional_test:
….do something
- conditional test in the first line and action in the indented block following the test
- for example, variable representing a person’s age, and we test if the person is old enough to vote
voting.py
age = 19
if age >= 18:
….print(“You are old enough to vote!”)
You are old enough to vote!
- indentation plays the same role in if statements as it did in for loops, all indented lines after an if statement will be executed if the test passes, and the entire block of indented lines will be ignored if the test fails
age = 19
if age >= 18:
….print(“You are old enough to vote!”)
….print(“Have you registered to vote yet?”)
You are old enough to vote!
Have you registered to vote yet?
- if the value of age is less than 18, this program would produce no output
if-else statements
- often, you’ll want to take one action when a conditional test passes and a different action in all other cases
- if-else – else statement allows you to define an action or set of actions that are executed when the conditional test fails
age = 17
if age >= 18:
….print(“You are old enough to vote!”)
….print(“Have you registered to vote yet?”)
else:
….print(“Sorry, you are too young to vote.”)
….print(“Please register to vote as soon as you turn 18!”)
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
- if-else structure works well in situations in which you want Python to always execute one of two possible actions
The if-elif-else chain
- if-elif-else – used to test and evaluate more than two possible situations
- Python only executes one block in an if-elif-else chain
- runs each conditional test in order, until one passes
- After a test passes Python skips the rest of the tests
- many real-world situations involve more than two possible conditions
- for example, consider an amusement park that charges different rates for different age groups
- admission for anyone under age 4 is free
- admission for anyone between the ages of 4 and 18 is $25
- admission for anyone age 18 or older is $40
- here’s how to use an if statement to determine a person’s admission rate
amusement_park.py
age = 12
if age < 4:
….print(“Your admission cost is $0.”)
elif page < 18:
….print(“Your admission cost is $25.”)
else:
….print(“Your admission cost is $40.”)
Your admission cost is $25.
- rather than printing the admission price within the if-elif-else block, it would be more concise to set just the price inside the if-elif-else chain and then have a single print() call that runs after the chain has been evaluated
age = 12
if age < 4:
….price = 0
elif age < 18:
….price = 25
else:
….price = 40
print(f”Your admission cost is ${price}.”)
- same result, but if-elif-else chain is narrower
- instead of determining a price and displauin a message, it simply determines the admission price
- more efficient and revised code is easier to modify
- to change the text of the output message, you would need to change only one print() call rather than three separate print() calls
Using multiple elif blocks
- can use many elif blocks in code
- for example, if the amusement park were to implement a discount for seniors, you could add on more conditional test to the code to determine whether someone qualifies for the senior discount
- anyone 65 or older pays half the regular admission or $20
age = 12
if age < 4:
….price = 0
elif age < 18:
….price = 25
elif age < 65:
….price = 40
else:
….price = 20
print(f”Your admission cost is ${price}.”)
Omitting the else block
- Python does not require an else block at the end of an if-elif chain
- sometimes, an else block is useful
- other times, it’s clearer to use an additional elif statement that catches the specific condition of interest
age = 12
if age < 4:
….price = 0
elif age < 18:
….price = 25
elif age < 65:
….price = 40
elif age >= 65:
….price = 20
print(f”Your admission cost is ${price}.”)
- every block of code must pass a specific test to be executed
- the else block is a catchall statement, it matches any condition that wasn’t matched by a specific if or elif test, and that can include invalid or even malicious data
- if you have a specific final condition you’re testing for, consider using a final elif block and omit the else block
- you’ll be more confident that your code will run only under the correct conditions
Testing multiple conditions
- if-elif-else chain is powerful, but it’s only appropriate to use when you just need one test to pass
- sometimes it’s important to check all conditions of interest
- in this case you should use a series of simple if statements with no elif or else blocks
- this technique makes sens when more than one condition could be True and you want to act on every condition that is True
- for example, if someone requests a two-topping pizza, you need to include both toppings on their pizza
toppings.py
requested_toppings = [‘mushrooms’, ‘extra cheese’]
if ‘mushrooms’ in requested_toppings:
….print(“Adding mushrooms.”)
if ‘pepperoni’ in requested_toppings:
….print(“Adding pepperoni.”)
if ‘extra cheese’ in requested_toppings:
….print(“Adding extra chees.”)
print(“\nFinished making your pizza!”)
- start with a list of requested toppings
- first if the statement checks to see whether the person requested mushrooms on their pizza
- test for pepperoni is another simple if statement, not an elif or else statement, so this test is run regardless of whether the previous test passed or not
- last if statement checks whether extra cheese was requested, regardless of the results from the first two tests
- three independent tests are executed every time this program is run
- because every condition in this example is evaluated, both mushrooms and extra cheese are added to the pizza:
Adding mushrooms.
Adding extra cheese.
Finished making your pizza!
- this wouldn’t work with an if-elif-else block because the code would stop running after only one test passes
- it would look like this
requested_toppings = [‘mushrooms’, ‘extra cheese’]
if ‘mushrooms’ in requested_toppings:
….print(“Adding mushrooms.”)
elif ‘pepperoni’ in requested_toppings:
….print(“Adding pepperoni.”)
elif ‘extra cheese’ in requested_toppings:
….print(“Adding extra cheese.”)
print(“\nFinished making your pizza!”)
- since the test for ‘mushrooms’ passed, extra cheese and pepperoni are never checked because Python doesn’t run any tests beyond the first test that passes in an if-elif-else chain
Adding mushrooms.
Finished making your pizza!
- if you only want one block of code to run, use an if-elif-else chain
- if more than one block of code needs to run, use a series of independent if statements
Using if statements with lists
- can do interesting work when you combine lists and if statements
- for example, you can efficiently manage changing conditions, such as the availability of certain times in a restaurant throughout a shift
- begin to prove that your code works as expected in all possible situations
Checking for special items
- can watch for special values in a list and handle those values appropriately
- pizzeria displays a message whenever a topping is added to your pizza as it’s being made
- code for this action can be written efficiently by making a list of toppings the customer has requested and using a loop to announce each topping as it’s added to the pizza
toppings.py
requested_toppings = [‘mushrooms’, ‘green peppers’, ‘extra cheese’]
for requested_topping in requested_toppings:
….print(f”Adding {requested_topping}.”)
print(“\nFinished making your pizza!”)
- output is straightforward because this code is just a simple for loop:
Adding mushrooms.
Adding green peppers.
Adding extra cheese.
Finished making your pizza!
- what if the pizzeria runs out of green peppers?
- an if statement inside the for loop can handle this situation appropriately
requested_toppings = [‘mushrooms’, ‘green peppers’, ‘extra cheese’]
for requested_topping in requested_toppings:
….if requested_topping == ‘green peppers’:
……..print(“Sorry, we are out of green peppers right now.”)
….else:
……..print(f”Adding {requested_topping}.”)
print(“\nFinished making your pizza!”)
- this time, we check each requested item before adding it to the pizza
- the if statement checks to see if the person requested green peppers
- if so, we display a message informing them why they can’t have green peppers
- the else block ensures that all other toppings will be added to the pizza
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!
End of study session.