5-1. Conditional Tests: Write a series of conditional tests.
Print a statement
describing each test and your prediction for the results of each test. Your code
should look something like this:
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')
• Look closely at your results, and make sure you understand why each line
evaluates to True or False.
• Create at least 10 tests. Have at least 5 tests evaluate to True and another
5 tests evaluate to False.
5-2. More Conditional Tests: You don’t have to limit the number of tests you
create to 10. If you want to try more comparisons, write more tests and add
them to conditional_tests.py. Have at least one True and one False result for
each of the following:
• Tests for equality and inequality with strings
• Tests using the lower() function
• Numerical tests involving equality and inequality, greater than and
less than, greater than or equal to, and less than or equal to
• Tests using the and keyword and the or keyword
• Test whether an item is in a list
• Test whether an item is not in a list
if Statements
When you understand conditional tests, you can start writing if statements.
Several different kinds of if statements exist, and your choice of which to
use depends on the number of conditions you need to test. You saw several
examples of if statements in the discussion about conditional tests, but now
let’s dig deeper into the topic.
Simple if Statements
The simplest kind of if statement has one test and one action:
if conditional_test:
do something
if Statements 83
You can put any conditional test in the first line and just about any
action in the indented block following the test. If the conditional test
evaluates to True, Python executes the code following the if statement.
If the test evaluates to False, Python ignores the code following the if
statement.
Let’s say we have a variable representing a person’s age, and we want to
know if that person is old enough to vote. The following code tests whether
the person can vote:
[Link] age = 19
u if age >= 18:
v print("You are old enough to vote!")
At u Python checks to see whether the value in age is greater than or
equal to 18. It is, so Python executes the indented print statement at v:
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 does
not pass.
You can have as many lines of code as you want in the block follow-
ing the if statement. Let’s add another line of output if the person is old
enough to vote, asking if the individual has registered to vote yet:
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
The conditional test passes, and both print statements are indented, so
both lines are printed:
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 dif-
ferent action in all other cases. Python’s if-else syntax makes this possible.
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
conditional test fails.
84 Chapter 5
We’ll display the same message we had previously if the person is old
enough to vote, but this time we’ll add a message for anyone who is not
old enough to vote:
age = 17
u if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
v else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
If the conditional test at u passes, the first block of indented print
statements is executed. If the test evaluates to False, the else block at v is
executed. Because age is less than 18 this time, the conditional test fails and
the code in the else block is executed:
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
This code works because it has only two possible situations to evaluate:
a person is either old enough to vote or not old enough to vote. The if-else
structure works well in situations in which you want Python to always execute
one of two possible actions. In a simple if-else chain like this, one of the two
actions will always be executed.
The if-elif-else Chain
Often, you’ll need to test more than two possible situations, and to evaluate
these you can use Python’s if-elif-else syntax. Python executes only one
block in an if-elif-else chain. It runs each conditional test in order until
one passes. When a test passes, the code following that test is executed and
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 $5.
• Admission for anyone age 18 or older is $10.
How can we use an if statement to determine a person’s admission rate?
The following code tests for the age group of a person and then prints an
admission price message:
amusement_ age = 12
[Link]
u if age < 4:
print("Your admission cost is $0.")
if Statements 85
v elif age < 18:
print("Your admission cost is $5.")
w else:
print("Your admission cost is $10.")
The if test at u tests whether a person is under 4 years old. If the test
passes, an appropriate message is printed and Python skips the rest of the
tests. The elif line at v is really another if test, which runs only if the pre-
vious test failed. At this point in the chain, we know the person is at least
4 years old because the first test failed. If the person is less than 18, an
appropriate message is printed and Python skips the else block. If both
the if and elif tests fail, Python runs the code in the else block at w.
In this example the test at u evaluates to False, so its code block is not
executed. However, the second test evaluates to True (12 is less than 18) so
its code is executed. The output is one sentence, informing the user of the
admission cost:
Your admission cost is $5.
Any age greater than 17 would cause the first two tests to fail. In these
situations, the else block would be executed and the admission price would
be $10.
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 simple print statement that runs after the chain has been
evaluated:
age = 12
if age < 4:
u price = 0
elif age < 18:
v price = 5
else:
w price = 10
x print("Your admission cost is $" + str(price) + ".")
The lines at u, v, and w set the value of price according to the person’s
age, as in the previous example. After the price is set by the if-elif-else chain,
a separate unindented print statement uses this value to display a mes-
sage reporting the person’s admission price.
This code produces the same output as the previous example, but the
purpose of the if-elif-else chain is narrower. Instead of determining a
price and displaying a message, it simply determines the admission price.
In addition to being more efficient, this revised code is easier to modify
than the original approach. To change the text of the output message, you
would need to change only one print statement rather than three separate
print statements.
86 Chapter 5
Using Multiple elif Blocks
You can use as many elif blocks in your code as you like. For example, if the
amusement park were to implement a discount for seniors, you could add
one more conditional test to the code to determine whether someone quali-
fied for the senior discount. Let’s say that anyone 65 or older pays half the
regular admission, or $5:
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
u elif age < 65:
price = 10
v else:
price = 5
print("Your admission cost is $" + str(price) + ".")
Most of this code is unchanged. The second elif block at u now checks
to make sure a person is less than age 65 before assigning them the full
admission rate of $10. Notice that the value assigned in the else block at v
needs to be changed to $5, because the only ages that make it to this block
are people 65 or older.
Omitting the else Block
Python does not require an else block at the end of an if-elif chain. Some-
times an else block is useful; sometimes it is 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 = 5
elif age < 65:
price = 10
u elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
The extra elif block at u assigns a price of $5 when the person is 65 or
older, which is a bit clearer than the general else block. With this change,
every block of code must pass a specific test in order to be executed.
if Statements 87
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 sometimes include
invalid or even malicious data. If you have a specific final condition you are
testing for, consider using a final elif block and omit the else block. As a
result, you’ll gain extra confidence that your code will run only under the
correct conditions.
Testing Multiple Conditions
The if-elif-else chain is powerful, but it’s only appropriate to use when you
just need one test to pass. As soon as Python finds one test that passes, it
skips the rest of the tests. This behavior is beneficial, because it’s efficient
and allows you to test for one specific condition.
However, sometimes it’s important to check all of the conditions of
interest. In this case, you should use a series of simple if statements with no
elif or else blocks. This technique makes sense when more than one condi-
tion could be True, and you want to act on every condition that is True.
Let’s reconsider the pizzeria example. If someone requests a two-topping
pizza, you’ll need to be sure to include both toppings on their pizza:
[Link] u requested_toppings = ['mushrooms', 'extra cheese']
v if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
w if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
x if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
We start at u with a list containing the requested toppings. The if
statement at v checks to see whether the person requested mushrooms
on their pizza. If so, a message is printed confirming that topping. The
test for pepperoni at w 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. The code at x checks whether extra cheese was requested regard-
less of the results from the first two tests. These 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!
88 Chapter 5
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. Here’s what
that would look like:
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!")
The test for 'mushrooms' is the first test to pass, so mushrooms are added
to the pizza. However, the values '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. The customer’s first topping will be added,
but all of their other toppings will be missed:
Adding mushrooms.
Finished making your pizza!
In summary, if you want only 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.