If Statements
Programming often involves examining a set of conditions and deciding which action to take based on those conditions. Python's if
statement allows you to examine the current state of a program and respond appropriately to that state.
A Simple Example
# Conditional formatting based on car type
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
Output:
Audi
BMW
Subaru
Toyota
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.
Checking for Equality
# Test for equality
car = 'bmw'
print(car == 'bmw') # True
car = 'audi'
print(car == 'bmw') # False
Case Sensitivity in Tests
Testing for equality is case sensitive in Python:
# Case-sensitive comparison
car = 'Bmw'
print(car == 'bmw') # False
# Convert to lowercase for comparison
car = 'Bmw'
print(car.lower() == 'bmw') # True
print(car) # Original value unchanged: 'Bmw'
Checking for Inequality
# Test for inequality
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
Output:
Hold the anchovies!
Numerical Comparisons
# Numerical comparisons
answer = 17
if answer != 42:
print("That is not the correct answer.")
a = 0
b = 10
print(a > b) # False
print(b >= a) # True
You can use these comparison operators:
==
(equal to)!=
(not equal to)>
(greater than)>=
(greater than or equal to)<
(less than)<=
(less than or equal to)
Checking Multiple Conditions
Using and
to Check Multiple Conditions
# Both conditions must be True
a = 0
b = 10
print(a > 1 and b > 5) # False (first condition is False)
Using or
to Check Multiple Conditions
# At least one condition must be True
a = 0
b = 10
print(a > 1 or b > 5) # True (second condition is True)
Checking Whether a Value is in a List
# Check if value is in list
animals = ['cat', 'dog', 'pig']
print('cat' in animals) # True
print('tiger' in animals) # False
Checking Whether a Value is Not in a List
# Check if value is not in list
animals = ['cat', 'dog', 'pig']
print('cat' not in animals) # False
print('tiger' not in animals) # True
Boolean Expressions
A Boolean expression is just another name for a conditional test:
# Boolean values
a = True
b = False
print(a, b) # True False
If Statements
Simple if Statements
The simplest kind of if
statement has one test and one action:
# Basic if statement
a = 10
if a > 0:
print('Yes, a > 0.')
Output:
Yes, a > 0.
if-else Statements
An if-else
block is similar to a simple if
statement, but the else
statement allows you to define an action that should be taken when the conditional test fails:
# if-else statement
a = 10
if a > 0:
print('Yes')
else:
print('No')
Output:
Yes
if-elif-else Chain
Often, you'll need to test more than two possible situations. Python's if-elif-else
chain makes this possible:
# if-elif-else chain
age = 12
if age < 4:
print("$0")
elif age < 18:
print("$25")
else:
print("$45")
Output:
$25
You can also store the result in a variable:
# Store result in variable
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
else:
price = 45
print(f"Your cost is ${price}")
Output:
Your cost is $25
Using Multiple elif Blocks
You can use as many elif
blocks as you need:
# Multiple elif blocks
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. The else
block is a catchall statement that matches any condition that wasn't matched by a specific if
or elif
test.
Using if Statements with Lists
Checking for special values in a list and handling them appropriately is one task you'll do again and again when you're working with lists:
# Handling special cases in a list
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!")
Output:
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!
Checking That a List is Not Empty
# Check for empty list
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
Using Multiple Lists
# Working with multiple lists
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print(f"Adding {requested_topping}.")
else:
print(f"Sorry, we don't have {requested_topping}.")
print("\nFinished making your pizza!")
Styling Your if Statements
The PEP 8 style guide recommends the following approach for styling conditional tests:
- Use a single space around comparison operators:
==
,>=
,<=
- Don't put spaces around the inequality operators:
!=
For example:
# Good style
if age < 4:
# Avoid
if age<4:
Summary
In this chapter you learned how to:
- Write conditional tests using comparison operators
- Combine conditional tests using
and
andor
- Check whether values are or aren't in lists
- Write simple
if
statements,if-else
blocks, andif-elif-else
chains - Use conditional tests to handle special situations in lists
- Style your conditional tests according to PEP 8 guidelines
Conditional tests form the foundation of decision-making in programming, allowing your programs to respond appropriately to different situations.