1.6. FOR loop with IF statement#

Sometimes we don’t just want to do the same operation on every input - we might want to do different operations depending on some condition.

For this we need a statement of the form IF…THEN

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

1.6.2. Checking a condition#

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 returns True or False:

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

We can make a variable called month and set it to any string we like (we will need to do this to make our loop work):

month = "Eleventember"
print(month)
Eleventember

… and we can then check if month contains an r:

month = "Eleventember"
"r" in "month"
False

To summarize, "r" in month translates as:

  • 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 uncommment it and see

# month = "Bananas"
# r in "month"

1.6.3. IF statement#

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

Now can you make a for loop that checks every month and prints a sentence about whether to eat shellfish, as in the if statement above?

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

for i in range(12): # complete the code
    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