4-Conditions and Conditional Statements
4-Conditions and Conditional Statements
You have already seen that when you change the input value to a function, you often get a different output. For
instance, consider an add_five() function that just adds five to any number and returns the result.
Then add_five(7) will return an output of 12 (=7+5), and add_five(8) will return an output of 13 (=8+5). Note
that no matter what the input is, the action that the function performs is always the same: it always adds five.
But you might instead need a function that performs an action that depends on the input. For instance, you might
need a function add_three_or_eight() that adds three if the input is less than 10, and adds eight if the input is
10 or more. Then add_three_or_eight(1) will return 4 (= 1+3), but add_three_or_eight(11) will return 19
(=11+8). In this case, the action that the function performs varies with the input.
In this lesson, you will learn how to use conditions and conditional statements to modify how your functions run.
Conditions
In programming, conditions are statements that are either True or False . There are many different ways to
write conditions in Python, but some of the most common ways of writing conditions just compare two different
values. For instance, you can check if 2 is greater than 3.
In [1]:
print(2 > 3)
False
You can also use conditions to compare the values of variables. In the next code cell, var_one has a value of 1,
and var_two has a value of two. In the conditions, we check if var_one is less than 1 (which is False ), and
we check if var_two is greater than or equal to var_one (which is True ).
In [2]:
var_one = 1
var_two = 2
print(var_one < 1)
print(var_two >= var_one)
False
True
For a list of common symbols you can use to construct conditions, check out the chart below.
Symbol Meaning
== equals
!= does not equal
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Important Note: When you check two values are equal, make sure you use the == sign, and not the = sign.
"if" statements
The simplest type of conditional statement is an "if" statement. You can see an example of this in
the evaluate_temp() function below. The function accepts a body temperature (in Celcius) as input.
Then, if temp > 38 is True (e.g., the body temperature is greater than 38°C), the message is updated
to "Fever!" . Otherwise, if temp > 38 is False, then the message is not updated.
Finally, message is returned by the function.
In [3]:
def evaluate_temp(temp):
# Set an initial message
message = "Normal temperature."
# Update value of message only if temperature greater than 38
if temp > 38:
message = "Fever!"
return message
In the next code cell, we call the function, where the temperature is 37°C. The message is "Normal
temperature" , because the temperature is less than 38°C ( temp > 38 evaluates to False ) in this case.
In [4]:
print(evaluate_temp(37))
Normal temperature.
However, if the temperature is instead 39°C, since this is greater than 38°C, the message is updated
to "Fever!" .
In [5]:
print(evaluate_temp(39))
Fever!
The first level of indentation is because we always need to indent the code block inside a function.
The second level of indentation is because we also need to indent the code block belonging to the "if"
statement. (As you'll see, we'll also need to indent the code blocks for "elif" and "else" statements.)
Note that because the return statement is not indented under the "if" statement, it is always executed,
whether temp > 38 is True or False .
In [6]:
def evaluate_temp_with_else(temp):
if temp > 38:
message = "Fever!"
else:
message = "Normal temperature."
return message
In the next code cell, we call this new function, where the temperature is 37°C. In this case, temp > 38 evaluates
to False , so the code under the "else" statement is executed, and the Normal temperature. message is
returned.
In [7]:
print(evaluate_temp_with_else(37))
Normal temperature.
As with the previous function, we indent the code blocks after the "if" and "else" statements.
First checks if temp > 38 . If this is true, then the message is set to "Fever!" .
As long as the message has not already been set, the function then checks if temp > 35 . If this is true, then
the message is set to "Normal temperature." .
Then, if still no message has been set, the "else" statement ensures that the message is set to "Low
temperature." message is printed.
You can think of "elif" as saying ... "okay, that previous condition (e.g., temp > 38 ) was false, so let's check if this
new condition (e.g., temp > 35 ) might be true!"
In [8]:
def evaluate_temp_with_elif(temp):
if temp > 38:
message = "Fever!"
elif temp > 35:
message = "Normal temperature."
else:
message = "Low temperature."
return message
In the code cell below, we run the code under the "elif" statement, because temp > 38 is False , and temp >
35 is True . Once this code is run, the function skips over the "else" statement and returns the message.
In [9]:
evaluate_temp_with_elif(36)
Out[9]:
'Normal temperature.'
Finally, we try out a case where the temperature is less than 35°C. Since the conditionals in the "if" and "elif"
statements both evaluate to False , the code block inside the "else" statement is executed.
In [10]:
evaluate_temp_with_elif(34)
Out[10]:
'Low temperature.'
Example - Calculations
In the examples so far, conditional statements were used to decide how to set the values of variables. But you can
also use conditional statements to perform different calculations.
In this next example, say you live in a country with only two tax brackets. Everyone earning less than 12,000 pays
25% in taxes, and anyone earning 12,000 or more pays 30%. The function below calculates how much tax is
owed.
In [11]:
def get_taxes(earnings):
if earnings < 12000:
tax_owed = .25 * earnings
else:
tax_owed = .30 * earnings
return tax_owed
print(ana_taxes)
print(bob_taxes)
2250.0
4500.0
In each case, we call the get_taxes() function and use the value that is returned to set the value of a variable.
For ana_taxes , we calculate taxes owed by a person who earns 9,000. In this case, we call
the get_taxes() function with earnings set to 9000 . Thus, earnings < 12000 is True ,
and tax_owed is set to .25 * 9000 . Then we return the value of tax_owed .
For bob_taxes , we calculate taxes owed by a person who earns 15,000. In this case, we call
the get_taxes() function with earnings set to 15000 . Thus, earnings < 12000 is False ,
and tax_owed is set to .30 * 15000 . Then we return the value of tax_owed .
Before we move on to another example - remember the add_three_or_eight() function from the introduction?
It accepts a number as input and adds three if the input is less than 10, and otherwise adds eight. Can you figure
out how you would write this function? Once you have an answer, click on the "Show hidden code" button below to
see the solution.
Note: This function should not be used as medical advice, and represents a fake medication.
In [14]:
def get_dose(weight):
# Dosage is 1.25 ml for anyone under 5.2 kg
if weight < 5.2:
dose = 1.25
elif weight < 7.9:
dose = 2.5
elif weight < 10.4:
dose = 3.75
elif weight < 15.9:
dose = 5
elif weight < 21.2:
dose = 7.5
# Dosage is 10 ml for anyone 21.2 kg or over
else:
dose = 10
return dose
The next code cell runs the function. Make sure that the output makes sense to you!
In this case, the "if" statement was False , and all of the "elif" statements evaluate to False , until we get
to weight < 15.9 , which is True , and dose is set to 5.
Once an "elif" statement evaluates to True and the code block is run, the function skips over all remaining
"elif" and "else" statements. After skipping these, all that is left is the return statement, which returns the value
of dose .
The order of the elif statements does matter here! Re-ordering the statements will return a very different
result.
In [15]:
print(get_dose(12))
5
Make sure this makes sense to you! Once you're ready, use the link below to move on to the exercise.
Your turn
Use what you have learned to write your own conditionals and conditional statements.
Have questions or comments? Visit the course discussion forum to chat with other learners.