3.12 If Statements

Sometimes, we only want to perform an operation if a condition is met. To do this, we can use the if statement, which is structured as such:

if <condition>:
    {do something}

The <condition> above is a statement that evaluates to a Boolean (i.e. True or False). As such, the comparison expressions we have seen previously (>, ==, !=, <=, etc.) are common components of an if statement. For example:

my_number = 3

if my_number < 4:
  print("Less than 4")
## Less than 4
if my_number > 5:
  print("Greater than 5")

The first statement is true: 3 is less than 4. As a result, the first print statement is executed. The second statement is false. It is therefore not executed.

Another use of conditions is checking whether a list contains a value of interest. For this, we can use in:

first_number = 3
second_number = 5
list_1 = [2,3,4]

if first_number in list_1:
  print("first number is in the list")
## first number is in the list
if second_number in list_1:
  print("second number is in the list") 

3.12.1 Else

What if we want to perform an action if a condition is met, and a different action if the condition is not met?

We can do this using the else statement:

if <condition>:
  {do something}
else:
  {do something different}  

For example, we can imagine a scenario in which the birth rate in a population depends on the current population size, where we can set the birth rate to one of two values whether the current population is above or below a threshold:

current_pop_size = 450

if current_pop_size >= 500:
  birth_rate = 0.6
else:
  birth_rate = 0.2

print(birth_rate)  

3.12.2 Else If

What if we want to check more than one condition? For this, we have the else if statement, which is structured as such:

if <condition>:
  {do something}
elif <second condition>:
  {do something different}

We can string together any number of else if statments. Going back to our birth rate example, what if instead of just two possible birth rates, we wanted a gradient of options? We could write something like this:

current_pop_size = 450

if current_pop_size >= 500:
  birth_rate = 0.6
elif current_pop_size >= 400:
  birth_rate = 0.5
elif current_pop_size >= 300:
  birth_rate = 0.3
else:
  birth_rate = 0.2

Here, the first statement is false (population size is less than 500), so we move on. The second statement is true (the population size is greater than 400). We set the birth rate to 0.5, and all subsequent elif and else statements are ignored.

Notice that the second elif statement (elif current_pop_size >= 300) is true. But we never actually evaluate this – once we hit a single true statement, the following elif statements are not evaluated.