1.6. FOR loop with IF statement#

This page (and subsequent pages) is a Jupyter Notebook. Download it or open it in Colab so you can actually run the code blocks!

Remember, there’s no way you can actually “break” anything, so don’t be afraid to edit things within this notebook. Errors are not necessarily a bad thing (even if they do look scary), have a go at working through some of the examples below. Today is not about understanding all of the specifics or the exact code you will be confronted with, but rather its important to try things out before the course starts so we can be sure you have a working set up for next week

What is an If statement?

So far, we’ve seen how a for loop lets us repeat an action many times. But sometimes, instead of repeating, we want the computer to make a choice — to do one thing if a condition is true, and something else otherwise. That’s where an if statement comes in.

An if statement checks whether a condition holds (for example, “is this number greater than 10?”). If the answer is yes, Python runs the block of code underneath. If not, it skips it.

So while a for loop controls how many times code runs, an if statement controls whether a piece of code runs at all, based on a condition.

Combining For Loops and If Statements

By combining for loops with if statements when we can loop through many items and apply conditions to each one. This is especially useful when working with data, because we often don’t want to just do the same operation on every iteration but instead we might want to do slightly different operations depending on some condition.

Try working through the code below to learn more about if statements and how they can be combined with for loops

1.6.1. Set up Python libraries#

As usual, run the code cell below to import the relevant Python libraries

# Set-up Python libraries - you need to run this but you don't need to change it
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import pandas as pd
import seaborn as sns
sns.set_theme(style='white')
import statsmodels.api as sm
import statsmodels.formula.api as smf
import warnings 
warnings.simplefilter('ignore', category=FutureWarning)

1.6.2. Truth in Coding#

In coding, many decisions come down to whether something is true or false. These are called Booleans (named after the mathematician George Boole). Python has two special keywords for this:

  • True

  • False

These are the only two Boolean values and they are sometimes represented as 1s and 0s. They often come from comparisons, like checking whether one number is bigger than another:

print(5>3)
True

Conditions in Python aren’t limited to numbers — we can also test membership and relationships between items. The keyword in checks whether something is contained inside a list, string, or other collection:

As an example, it is said that you should only eat shellfish in months that don’t have “r” in the name. We can check whether a word has an r in the name using the test in, which will return True or False:

"r" in "January"
True
"r" in "May"
False

Try creating a variable called month and setting this to any string you like. To make sure this new variable works simply use the print function:

month = "Eleventember"
print(month)
Eleventember

Now check if the month contains an r. Change the value of month and rerun the code severak times to confirm you understand.

month = "Blue"
"r" in month
False

To summarize, when you write the code "r" in month the value of this statement is a Boolean: i.e., either True or False

  • if there is an r in the string contained in the variable month, return True

  • otherwise return False

Comprehension#

a. what will happen if I run this code block?

  • Think first, the uncomment it and see, careful, theres a trick!

#month = "rice"
#"r" in "month"

1.6.3. IF statement#

As previously mentioned if statements will execute the code below when the condition of the if statment is True, you can combine this with an else statement or an else if (elif) to cover other possibilities. Specifically an else runs if none of the previous conditions were trye and elif lets you check for additional specific conditions.

Try changing the condition variable below and see what happens:

condition = True

if condition:
    print('You will only see this printed if the condition was True')
You will only see this printed if the condition was True
condition = False

if condition:
    print('here the condition was True')
else:
    print('here the condition was False')
here the condition was False

Next we can set up an if statement to print different statements depending on whether there is an r in the name of the month

month = "August"

if ("r" in month):
    print('Don\'t eat shellfish in ' + month)
else:
    print('Do eat shellfish in ' + month)   
Do eat shellfish in August

Rather than only checking whether it is safe to eat shellfish 1 month at a time, it would be most convenient to loop through all of the months and check whether there is an r in each months name. To do this, we will use an if statment together with a for loop.

First you will need to create a list of all of the months you want to check, use a for loop like we used previously , and now include an if statement that is executed on each iteration through the months.

months=['January','February','March','April','May','June',
        'July','August','September','October','November','Decemeber']

for i in range(len(months)): # 
    if ("r" in months[i]): 
        print('Don\'t eat shellfish in ' + months[i])
    else:
        print('Do eat shellfish in ' + months[i]) 
        
Don't eat shellfish in January
Don't eat shellfish in February
Don't eat shellfish in March
Don't eat shellfish in April
Do eat shellfish in May
Do eat shellfish in June
Do eat shellfish in July
Do eat shellfish in August
Don't eat shellfish in September
Don't eat shellfish in October
Don't eat shellfish in November
Don't eat shellfish in Decemeber

Comprehension#

Lets break the code above and make sure you know what is happening. For each code chunk below try to guess what the result will be. Think first, then uncomment it and see if you are correct

#len(months)
#i = 4
#print(months[i])