5 INTRO IfStatements
5 INTRO IfStatements
5 INTRO IfStatements
March 3, 2024
If you have a list of cars and you want to print out the name of each car.
Car names are proper names, so the names of most cars should be printed in title case.
However, the value “bmw” should be printed in all uppercase.
if car == "bmw":
print(car.upper())
# If the value of car is anything other than "bmw", it’s printed in title␣
↪case.
else:
print(car.title())
Audi
BMW
Subaru
Toyota
2 Conditional Tests
• At the heart of every if statement is an expression that can be evaluated as “True” or “False”
and is called a “conditional test”.
• Python uses the values True and False to decide whether the code in an if statement should
be executed.
• If a conditional test evaluates to True, Python executes the code following the if statement.
1
2.1 Checking for Equality
The simplest conditional test checks whether the value of a variable is equal to the value of interest.
# Check whether the value of car is "bmw" - using a "double" equal sign (==)
car == "bmw"
True
False
False
But if case doesn’t matter and instead you just want to test the value of a variable.
You can convert the variable’s value to “lowercase” before doing the comparison.
[ ]: car = "Audi"
print(car.lower() == "audi") # Return "True".
True
2
2.3 Checking for Inequality
When you want to determine two values are not equal, you can use inequality operator (!=).
[ ]: requested_topping = "mushrooms"
False
True
False
True
[ ]: answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
The test on the left passes, but the test on the right fails, so the overall conditional expression
evaluates to False.
[ ]: Mark_age = 22
Andy_age = 16
False
3
Both individual tests pass, causing the overall conditional expression to evaluate as True.
[ ]: Mark_age = 22
Andy_age = 20
True
Because the test for “Mark_age >= 18” passes, the overall expression evaluates to True.
[ ]: Mark_age = 22
Andy_age = 16
True
Both tests now fail and the overall expression evaluates to False.
[ ]: Mark_age = 17
Andy_age = 16
False
True
False
4
2.7 Checking Whether a Value Is “Not in” a List
• Other times, it’s important to know if a value does not appear in a list.
• You can use the keyword “not in”.
[ ]: game_active = True
can_edit = False
print(game_active)
print(can_edit)
True
False
5
3 if Statements
3.1 Simple if Statements
• 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 does not pass.
if [conditional_test]:
[do something - conditional_test is True] ...
[ ]: age = 19
# Check to see whether the value of age is greater than or equal to 18.
if age >= 18:
print("You are old enough to vote!")
[ ]: age = 19
[ ]: age = 17
6
3.3 The if-elif-else Chain
If you want to test more than two possible situations, you can use “if-elif-else” statement.
[ ]: age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $120.")
else:
print("Your admission cost is $240.")
[ ]: age = 12
[ ]: age = 68
7
3.5 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 = 68
Adding mushrooms.
Adding extra cheese.
8
This code would not work properly if we used an if-elif-else block,because the code would stop
running after only one test passes.
Adding mushrooms.
Addind mushrooms.
Addind pineapples.
Addind extra cheese.
Addind mushrooms.
Sorry, we are out of pineapples right now.
Addind extra cheese.
9
4.2 Checking That a List Is Not Empty
• When “the name of a list” is used in an if statement, Python returns “True” if the list
contains “at least one item”; an empty list evaluates to False.
• For the values 0, None, single-quote empty string ’ ’, double-quote empty string ““, empty
list [ ], empty tuple ( ) and empty dictionary { }, Python will return”False“.
[ ]: requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print(f"Addind {requested_topping}.")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
Addind mushrooms.
Sorry, we don't have french fries.
Addind extra cheese.
References:
• Eric Matthes - Python Crash Course-No Starch Press (2023)
10