Making choices with conditional statements

Notes:



cereal[cereal['mfr'] == 'K']
                         name mfr  type  calories  protein  fat  sodium  fiber  carbo  sugars  potass  vitamins  shelf  weight  cups     rating
2                    All-Bran   K  Cold        70        4    1     260    9.0    7.0       5     320        25      3    1.00  0.33  59.425505
3   All-Bran with Extra Fiber   K  Cold        50        4    0     140   14.0    8.0       0     330        25      3    1.00  0.50  93.704912
6                 Apple Jacks   K  Cold       110        2    0     125    1.0   11.0      14      30        25      2    1.00  1.00  33.174094
16                Corn Flakes   K  Cold       100        2    0     290    1.0   21.0       2      35        25      1    1.00  1.00  45.863324
17                  Corn Pops   K  Cold       110        1    0      90    1.0   13.0      12      20        25      2    1.00  1.00  35.782791
..                        ...  ..   ...       ...      ...  ...     ...    ...    ...     ...     ...       ...    ...     ...   ...        ...
58                Raisin Bran   K  Cold       120        3    1     210    5.0   14.0      12     240        25      2    1.33  0.75  39.259197
60             Raisin Squares   K  Cold        90        2    0       0    2.0   15.0       6     110        25      3    1.00  0.50  55.333142
62              Rice Krispies   K  Cold       110        2    0     290    0.0   22.0       3      35        25      1    1.00  1.00  40.560159
66                     Smacks   K  Cold       110        2    1      70    1.0    9.0      15      40        25      2    1.00  0.75  31.230054
67                  Special K   K  Cold       110        6    0     230    1.0   16.0       3      55        25      1    1.00  1.00  53.131324

[23 rows x 16 columns]

Notes:

In the last Module, we explored the different data types and structures that Python offers.

It’s at this point in the course where we learn how to ask Python to make a decision, depending on conditions.

We did something similar when we filtered a dataframe using conditions like finding all the rows with a specific column value.


my_name = 'Hayley' 

if my_name.lower() == 'hayley':
    print('My name is Hayley too!')
elif my_name.lower() == 'totoro':
    print('Interesting, I loved that movie!')
else:
    print("That's a great name.")
  
print('Nice to meet you!')
My name is Hayley too!
Nice to meet you!

Notes:

Let’s start with an example of what the syntax looks like.

Perhaps we want to introduce ourselves in our code by using the object called my_name.

We’ve assigned 'Hayley' to the object my_name in this example.

We use a verb called print() that simply prints the object or string set as an argument.

We can see that since the object my_name is equal to Hayley, the output is My name is Hayley too, followed by the regular non-conditional code Nice to meet you!.


module5/iftrue.png

Notes:

Python looks at the first condition if my_name.lower() == 'Hayley' and since it evaluates to True, it prints the code under the statement, which is 'My name is Hayley too!'

Python passes the other print() statements from the elif and else conditions and continues to run the regular code 'Nice to meet you!.


my_name = 'Totoro' 

if my_name.lower() == 'hayley':
    print('My name is Hayley too!')
elif my_name.lower() == 'totoro':
    print('Interesting, I loved that movie!')
else:
    print("That's a great name.")
  
print('Nice to meet you!')
Interesting, I loved that movie!
Nice to meet you!

Notes:

Now what happens if the object is equal to something else?

This time, the object my_name has a value now of Totoro.

We see the output is Interesting, I loved that movie! Nice to meet you!

What is happening here?


module5/eliftrue.png

Notes:

Python ignores the code under the first condition if my_name.lower() == 'hayley' since it evaluates to False.

Instead, Python continues to the next condition elif my_name.lower() == 'totoro'which is True. It then executes the code under it, which prints 'Interesting, I loved that movie!'.

Python then skips over the next lines of code and goes straight to printing 'Nice to meet you!'.


my_name = 'Desmond' 

if my_name.lower() == 'hayley':
    print('My name is Hayley too!')
elif my_name.lower() == 'totoro':
    print('Interesting, I loved that movie!')
else:
    print("That's a great name.")
  
print('Nice to meet you!')
That's a great name.
Nice to meet you!

Notes:

Now we try something that meets neither the first or second conditions.

When my_name is equal to Desmond, the first 2 conditions both evaluate to False, and the last condition executes and prints That's a great name..

It executes the regular code print('Nice to meet you!') just like before.


module5/elsetrue.png

Notes:

Here we see that neither the first or second conditions are met, so the else condition is executed before printing the regular non-conditioned code.


Syntax

my_name = 'Hayley' 

if my_name.lower() == 'hayley':
    print('My name is Hayley too!')
elif my_name.lower() == 'totoro':
    print('Interesting, I loved that movie!')
else:
    print("That's a great name.")
  
print('Nice to meet you!')
My name is Hayley too!
Nice to meet you!

Notes:

Python conditional statements contains 2 important things:

  • A strict structure.

  • The keyword if and optional keywords else and elif.


Structure

my_name = 'Hayley' 

if my_name.lower() == 'hayley':
    print('My name is Hayley too!')
My name is Hayley too!

The structure of a choice is as follows:

if SOME_BOOLEAN:
    statement body 

Notes:

The structure of a choice is as follows:

if SOME_BOOLEAN:
    statement body 

Each conditional expression must end with a colon : and code to be executed if the condition is met must all must be indented with 4 spaces (or consistent indentation) in the statement body.

In the example above:

if my_name.lower() == 'hayley' is the Boolean statement and

print("My name is Hayley too!") is the statement body.


Keywords - if, else

my_name = 'Mia' 

if my_name.lower() == 'hayley':
    print('My name is Hayley too!')
elif my_name.lower() == 'totoro':
    print('Interesting, I loved that movie!')
else:
    print("That's a great name.")
  
print('Nice to meet you!')
That's a great name.
Nice to meet you!

Notes:

An if keyword is needed for any conditional.

If the Boolean value is True, the body of the statement (which is anything indented under it) will be executed.

If the expression is False, the body of the statement is not executed, and it continues to the next line of non-indented code outside the body.

The else expression will execute if the conditional expressions above it are False.

The keyword else can only occur once following an if condition and are optional to the code.


Keywords - elif

my_name = 'Totoro' 

if my_name.lower() == 'hayley':
    print('My name is Hayley too!')
elif my_name.lower() == 'totoro':
    print('Interesting, I loved that movie!')
else:
    print("That's a great name.")
  
print('Nice to meet you!')
Interesting, I loved that movie!
Nice to meet you!

Notes:

elif stands for else if. It allows us to check if different conditions evaluate to True.

When the elif expression evaluates to True, then the body of the statement is executed, just like an if statement.

In the case we saw before when my_name = 'Totoro', the elif condition my_name.lower() == 'totoro' evaluates to True.


if my_name.lower() == 'hayley':
    print('My name is Hayley too!')
elif my_name.lower() == 'totoro':
    print('Interesting, I loved that movie!')
elif  my_name.lower() == 'Desmond':
    print("That's a great name.")
  
print('Nice to meet you!')
my_name = 'Hayley' 

elif my_name.lower() == 'totoro':
    print("Interesting, I loved that movie!")
Error: invalid syntax (<string>, line 2)

Notes:

Unlike else statements, elif statements can be used multiple times in a decision process.

But elif statements MUST always follow an if statement or an error will occur like we see here.


Order matters

item = 13 

if item > 10:
    magnitude = 'Between 10 and 20'
elif item > 20:
    magnitude = 'Greater than 20'
else:
    magnitude = '10 or less'
 
magnitude
'Between 10 and 20'

Notes:

The order we chose for the statement for the if and elif statements is important and can result in different outputs.

Let’s explore this in the next example using inequalities with numbers.

In this case, our item object, which equals 13 here, is greater than 10, so our first condition holds true, and so magnitude is assigned a value of 'Between 10 and 20'


item = 25 

if item > 10:
    magnitude = 'Between 10 and 20'
elif item > 20:
    magnitude = 'Greater than 20'
else:
    magnitude = '10 or less'
 
magnitude
'Between 10 and 20'

Notes:

Let’s see what happens with an item value equal to 25.

magnitude is still assigned a value of 'Between 10 and 20', but our item is greater than 20!


module5/order1.png

Notes:

item is taken out of the stream at first if condition, so it doesn’t get a chance to see the elif statement even though it would result in a True value.


item = 25 

if item > 20:
    magnitude = 'Greater than 20'
elif item > 10:
    magnitude = 'Between 10 and 20'
else:
    magnitude = '10 or less'
 
magnitude
'Greater than 20'

Notes:

This can be fixed by rearranging the conditional statements.

Instead, we put item > 20 as the first condition followed by the condition item > 10.

Now a value of 25 gives the desired output of greater than 20.


module5/order2.png

Notes:

Here we can see that the first condition is True and executes the code in the statement body - This statement body assigns the object magnitude a value of 'Greater than 20'.

Python then passes the other conditions and executes magnitude.


item = 13 

if item > 20:
    magnitude = 'Greater than 20'
elif item > 10:
    magnitude = 'Between 10 and 20'
else:
    magnitude = '10 or less'
 
magnitude
'Between 10 and 20'

Notes:

But what about if item was equal to 13?

In this case, magnitude results in a value of 'Between 10 and 20', which is what we expect.


module5/order3.png

Notes:

Since 13 doesn’t meet the first condition item > 20, Python passes it and moves onto the second condition item > 10, which assigns magnitude the value Between 10 and 20.

It skips the else statement since one of the statements above was already evaluated to True.


Inline

item = 13

if  item > 10:
    magnitude = 'Greater than 10'
else:
    magnitude = '10 or less'
    
magnitude
'Greater than 10'
magnitude = "Greater than 10" if item > 10 else "10 or less"
magnitude
'Greater than 10'

Notes:

In situations where we have only if and else statements, we have the ability to put it all in a single line of code.

Let’s test this on our object item.

The original conditional statements below checks if the item is greater than 10 and assigns a value of greater than 10 if it’s True and a value of 10 or less otherwise.

The 4 lines used for the conditional statements can be compressed into a single one.

Both syntaxes are acceptable, depending on your preference.

This type of syntax is only possible for decisions that involve only if and else conditions.


Python Keyword “in”

exercises = ['burpees', 'lunges', 'squats', 'curls', 'deadlifts']

'squats' in exercises
True
if 'squats' in exercises:
    sore = "Extreme"
else:
    sore = "Not sore"
sore
'Extreme'

Notes:

We’ve already seen that conditions evaluate to a Boolean.

So far, we’ve seen a lot of Boolean evaluated from equalities and inequalities, but that’s not all.

There are many different keywords we can use to obtain a Boolean value, but one that you may use often is the keyword in.

We can use the keyword in to check if a certain value is contained in a list or dictionary.

We can pair this with a conditional statement like we did before to have Python makes decisions.

In this example, we are checking if squats is contained in our list exercises.

We can see that squats exists at position 2 in the list, and therefore the object sore is assigned a value of Extreme.


Let’s apply what we learned!

Notes: