5 INTRO IfStatements

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Introduction if statement

March 3, 2024

1 [if statements] A Simple Example


Programming often involves examining a set of conditions and deciding which action to take based
on those conditions.

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.

[ ]: cars = ["audi", "bmw", "subaru", "toyota"]

# Loop through a list of car names.


for car in cars:
# Check if the current value of car is "bmw", then the value is printed in␣
↪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.

[ ]: # Set the value of car to "bmw" - using a "single" equal sign


car = "bmw"

# Check whether the value of car is "bmw" - using a "double" equal sign (==)
car == "bmw"

# The values in this example match, so Python returns "True".


print(car == "bmw")

True

[ ]: # Set the value of car to "audi".


car = "audi"

# Is the value of car equal to "bmw" ?


car == "bmw"

print(car == "bmw") # Return "False".

False

2.2 Ignoring Case When Checking for Equality


• Testing for equality is case sensitive in Python.
• Two values with different capitalization are not considered equal.

[ ]: car = "Audi" # If case matters, this behavior is advantageous.


print(car == "audi") # Return "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"

# Return "True", because requested_topping != "anchovies".


if requested_topping != "anchovies":
print("Hold the anchovies!")

Hold the anchovies!

2.4 Numerical Comparisons


[ ]: age = 16
print(age == 18)
print(age != 18)
print(age >= 18)
print(age <= 18)

False
True
False
True

[ ]: answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")

That is not the correct answer. Please try again!

2.5 Checking Multiple Conditions


2.5.1 Using “and” to Check Multiple Conditions
• To check whether two conditions are both True “simultaneously”. the del if you know its
index.
• If each test passes, the overall expression evaluates to True.
• If either test fails or if both tests fail, the expression evaluates to False.

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

print(Mark_age >= 18 and Andy_age >= 18) # Return "False".

False

3
Both individual tests pass, causing the overall conditional expression to evaluate as True.

[ ]: Mark_age = 22
Andy_age = 20

print(Mark_age >= 18 and Andy_age >= 18) # Return "True".

True

2.5.2 Using “or” to Check Multiple Conditions


• The keyword or allows you to check multiple conditions as well, but it passes when either or
both of the individual tests pass.
• An or expression fails only when both individual tests fail.

Because the test for “Mark_age >= 18” passes, the overall expression evaluates to True.

[ ]: Mark_age = 22
Andy_age = 16

print(Mark_age >= 18 or Andy_age >= 18) # Return "True".

True
Both tests now fail and the overall expression evaluates to False.

[ ]: Mark_age = 17
Andy_age = 16

print(Mark_age >= 18 or Andy_age >= 18) # Return "False".

False

2.6 Checking Whether a Value Is “in” a List


• Sometimes it’s important to check whether a list contains a certain value before taking an
action.
• To find out whether a particular value is already in a list, use the keyword “in”.

[ ]: shopping_list = ["egg", "apple", "fish"]

print("egg" in shopping_list) # Return "True".


print("coffee" in shopping_list) # Return "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”.

[ ]: banned_users = ["andrew", "carolina", "david"]


user = "mark"

if user not in banned_users:


print(f"{user.title()}, you can post a response if you wish.")

Mark, you can post a response if you wish.

2.8 Boolean Expressions


• Boolean values are often used to keep track of certain conditions.
• A Boolean value is either “True” or “False”.

[ ]: 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!")

You are old enough to vote!

[ ]: age = 19

if age >= 18:


# Both print() calls are indented, so both lines are printed.
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?

3.2 if-else Statements


• An “if-else” block is similar to a simple “if” statement, but the “else” statement allows
you to define an action or set of actions that are executed when the condtional test fails.
• If the conditional test passes, the first block of indented print() calls is executed.
• If the test evaluates to False, the else block is executed.

[ ]: age = 17

if age >= 18:


print("You are old enough to vote!")
else:
print("Sorry, you are too young to vote.")

Sorry, you are too young to vote.

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

Your admission cost is $120.

[ ]: age = 12

if age < 4: # baby


price = 0
elif age < 18: # teenager
price = 120
else: # adult
price = 240

print(f"Your admission cost is ${price}.")

Your admission cost is $120.

3.4 Using Multiple elif Blocks


You can use as many elif blocks in your code as you like.

[ ]: age = 68

if age < 4: # baby


price = 0
elif age < 18: # teenager
price = 120
elif age < 65: # adult
price = 240
else: # elder
price = 80

print(f"Your admission cost is ${price}.")

Your admission cost is $80.

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

if age < 4: # baby


price = 0
elif age < 18: # teenager
price = 120
elif age < 65: # adult
price = 240
elif age >= 65: # elder
price = 80

print(f"Your admission cost is ${price}.")

Your admission cost is $80.

3.6 Testing Multiple Conditions


• The if-elif-else chain is powerful, but it’s only appropriate to use when you ust need
“one” test to pass.
• As soon as Python finds one test that passes, it skips the rest of the tests.
• However, 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”.

[ ]: requested_toppings = ["mushrooms", "extra cheese"]

# Simple if statement, not an elif or else statement


if "mushrooms" in requested_toppings:
print("Adding mushrooms.")
if "pineapples" in requested_toppings:
print("Adding pineapples.")
if "extra cheese" in requested_toppings:
print("Adding extra cheese.")

print("\nFinished making your pizza!")

Adding mushrooms.
Adding extra cheese.

Finished making your pizza!

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.

[ ]: requested_toppings = ["mushrooms", "extra cheese"]


if "mushrooms" in requested_toppings:
print("Adding mushrooms.")
# Python doesn’t run any tests beyond the first test that passes in an␣
↪if-elif-else chain.

elif "pineapples" in requested_toppings:


print("Adding pineapples.")
elif "extra cheese" in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")

Adding mushrooms.

Finished making your pizza!

4 Using if Statements with Lists


4.1 Checking for Special Items
[ ]: requested_toppings = ["mushrooms", "pineapples", "extra cheese"]
for requested_topping in requested_toppings:
print(f"Addind {requested_topping}.")
print("\nFinished making your pizza!")

Addind mushrooms.
Addind pineapples.
Addind extra cheese.

Finished making your pizza!


If the pizzeria runs out of “pineapples”?
• An if statement inside the for loop can handle this situation appropriately:

[ ]: requested_toppings = ["mushrooms", "pineapples", "extra cheese"]


for requested_topping in requested_toppings:
if requested_topping == "pineapples":
print(f"Sorry, we are out of {requested_topping} right now.")
else:
print(f"Addind {requested_topping}.")
print("\nFinished making your pizza!")

Addind mushrooms.
Sorry, we are out of pineapples right now.
Addind extra cheese.

Finished making your pizza!

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?")

Are you sure you want a plain pizza?

4.3 Using Multiple Lists


Let’s watch out for unusual topping requests before we build a pizza.

[ ]: available_toppings = ["mushrooms", "pineapples", "extra cheese", "freen␣


↪peppers", "olives", "tomatoes"]

requested_toppings = ["mushrooms", "french fries", "extra cheese"]

for requested_topping in requested_toppings:


if requested_topping in available_toppings:
print(f"Addind {requested_topping}.")
else:
print(f"Sorry, we don't have {requested_topping}.")

print("\nFinished making your pizza!")

Addind mushrooms.
Sorry, we don't have french fries.
Addind extra cheese.

Finished making your pizza!

References:
• Eric Matthes - Python Crash Course-No Starch Press (2023)

10

You might also like