Conditionals¶


fork-in-the-road.gif

Applied Review¶

Boolean Data Type¶

  • Remember that we have four primitive types in Python:
    • int - 0, 1, 2, 3, ...
    • float - 1.23, 2.45, 5.0, ...
    • string - 'hello', 'x', ...
    • boolean - True, False
  • Logical tests return boolean values True and False
In [1]:
1 < 0
Out[1]:
False
In [2]:
1 < 2
Out[2]:
True

Boolean Operators¶

  • Sometimes we want to combine logical tests, and we can do so with boolean operators
  • Two common boolean operators are:
    • and - test whether logical tests on the left and right side of operator are true
    • or - test whether at least one of the logical tests on the left or right side of the operator are true
In [3]:
1 < 2 and 2 < 3
Out[3]:
True
In [4]:
1 < 2 and 2 < 2
Out[4]:
False
In [5]:
1 < 2 or 2 < 2
Out[5]:
True
In [6]:
1 < 1 or 2 < 2
Out[6]:
False

General Model¶

Control Flow¶

  • Flow is to proceed or move
  • Control is to exercise restraining or directing influence over
Question: What is control flow?
  • Control flow is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated.
  • In other words, it's controlling the flow of the program execution.
  • There are two common ways to do this: conditionals and iteration.

Conditionals¶

  • Conditionals are directions on when to do something and when not to do something
  • They start with a yes/no (true/false) question (i.e. "Are you tired?")
  • And are followed with a direction depending on the result of the question (i.e. "Go to bed.", "Don't go to bed.")
conditionals-path.png

Iteration¶

  • Iteration is the repetition of a process
  • The process is generally repeated until a certain condition is met
  • Examples:
    • Count to 102
    • Count all of the floors of the Empire State Building
    • Keep walking down this road until you hit 5th Street

Conditionals in a Program¶

  • Conditionals can be used to control the flow of a program

Form¶

  • Within programs, conditionals usually take the form of if/then statements (i.e. "If you are tired, then go to bed.")
  • But they can also contain else statements (not statements) (i.e. "If you are tired, then go to bed. If not, stay up and read a book.")

Execution Pattern¶

conditionals-execution-path.png

Why Use Conditionals¶

Question: Why might we want to use conditionals in Python?
  • Data generation (case-when logic, etc.)
  • Direct when to run certain code (i.e. "If there are more than 5 flights from Cincinnati to New York, make a data visualization showing average delay time in flights from Cincinnati to New York")
  • Benefits include:
    • Error checking
    • Logic checking
    • Automation

Program Control¶

if Statements¶

  • if statement syntax in Python isn't quite as easy as our examples, but it's pretty close...
  • if statements begin with the if keyword and are followed by a logical test and a colon
if tired == 'Yes':
  • The then statement directly follows the if statement as an indented block
if tired == 'Yes':
    go_to_bed()
  • Note that the actual word then is never used - it's implied by the indent

  • Interpret as:

    if condition_holds:
        execute_code()
    
  • The implied then-block can have as many lines as necessary
if tired == 'Yes':
    brush_teeth()
    turn_off_lights()
    go_to_bed()
  • All of the indented code will execute only if tired == 'Yes' is True

Non psuedo code¶

In [7]:
x = 'tired'

if x == 'tired':
    print('Go to bed!')
Go to bed!

Your Turn¶

  1. Describe what this statement is doing.

    if denominator != 0:
        quotient = numerator / denominator
    
  2. Fill in the blanks to print the statement if x is a negative number. Re-run multiple times.

    import random
    
    x = random.randint(-10, 10)
    
    __ x _ __:
        print(f'x = {x}, which is negative')
    

else Statement¶

  • The else statement must follow an if statement and its indented then-block
  • Similar to the if statement, it begins with the else keyword and is followed by a colon
if tired == 'Yes':
    go_to_bed()
else:
    read_a_book()
  • Similar to if's then-block, there's also an indented block to be run if the else path is taken
Question: When will the else path be taken?

if tired == 'Yes':
    go_to_bed()
else:
    read_a_book()
  • The else path is taken in all cases when tired is not equal to 'Yes'

Your Turn¶

Fill in the blanks to print the relevant statement for x. Re-run multiple times.

import random

x = random.randint(-10, 10)

__ x _ __:
    print('x is negative')
__:
    print('x is positive')

elif Statement¶

  • There's another option available when working with conditionals in Python
  • The elif (else-if) statement can be used to add another if statement in the execution path
if tired == 'Yes':
    go_to_bed()
elif tired == 'A little':
    rest_eyes()
else:
    read_a_book()
  • You can include as many elif statements as you want
    • if you're familiar with a switch statement in other languages, this is Python's closest relative

Your Turn¶

Fill in the blanks to print the relevant statement for x.

import random

random.seed(7)
x = random.randint(-10, 10)

__ x _ __:
    print('x is negative')
__ x _ __:
    print('x is positive')
__:
    print('x is zero')

Nesting and Combining Statements¶

  • if-elif-else statements can be nested or combined to account for more complex logic

Nesting Statements¶

  • Assume you want to execute some code if tired == 'Yes' AND the time > 20:00, you can nest if statements
if tired == 'Yes':
    if time > 20:00:
        go_to_bed()
  • And you can include a nested else
if tired == 'Yes':
    if time > 20:00:
        go_to_bed()
    else:
        take_a_nap()

Combining Statements¶

  • Multiple statements can also be combined to a single line using logical operators rather than nested
if tired == 'Yes' and time > 20:00:
    go_to_bed()
if tired == 'Yes' and time <= 20:00:
    take_a_nap()
  • This will be equally efficient - it's a matter of personal preference and code readability

Variants of Conditional Tests¶

You will see a few common variants of our conditional test statement

Something is of a particular value¶

All our examples thus far fall into this category:

In [8]:
x = 7

if x > 0:
    print('x is positive')
x is positive
In [9]:
y = 'Ethan'

if y == 'Ethan':
    print('y is not Brad')
y is not Brad

Something is in¶

Sometimes we just want to know if a particular value exists in an object:

In [10]:
email = ['Ethan', 'Brad', 'spam']

if 'spam' in email:
    print('You have spam in your email!')
You have spam in your email!

Something is a particular object¶

Sometimes we only want to operate on a particular type of object:

In [11]:
isinstance(email, list)
Out[11]:
True
In [12]:
if isinstance(email, list):
    print(f'You have {len(email)} email')
You have 3 email
In [13]:
x = 3

if isinstance(x, (int, float)):
    print(x * 4)
else:
    print('x is not a number')
12

Something is¶

Sometimes we want to operate on an object ___only if___ it contains values:

In [14]:
# the truthiness of empty objects are equivalent to False or 0
empty_list = []

if empty_list:
    print('list is not empty')
else:
    print('list is empty')
list is empty
In [15]:
# we can use this to do control flow for objects that contain information
email = ['Ethan', 'Brad', 'spam']

if email:
    print('You have email!')
else:
    print('Get back to work!')
You have email!

All or some of something is¶

Sometimes we want to operate on an object if ___all___ or ___any___ of the values are True:

In [16]:
email_is_spam = [False, False, True]
In [17]:
# use `all()` or `any()`
if all(email_is_spam):
    print('All your emails are spam!')
elif any(email_is_spam):
    print('At least one of your emails is spam!')
else:
    print('No spam!')
At least one of your emails is spam!
Just realize there is a lot of flexibility!

Vectorized Control¶

  • So far, we've seen how conditionals can be used for program control flow
  • Recall that one of the benefits of conditionals is data creation
  • This often requires vectorization - operations that work on a one-dimensional object like a list or Series (DataFrame variable)

Vectorization¶

  • So far, we have focused on controlling the flow based on a single conditional statement
non-vectorized.png
  • Often we want to assess and execute code if that condition is TRUE across multiple elements (aka vectorized)
vectorized.png

Creating DataFrame Variables Conditionally¶

  • Recall that the numpy package is really powerful for working with numeric data in Python
In [18]:
import numpy as np
  • We can use the where() function from numpy to conditionally create data within data frames
  • Let's start by importing a data frame
In [19]:
import pandas as pd
planes_df = pd.read_csv('../data/planes.csv')
  • And recall our data and variables
In [20]:
planes_df.head(3)
Out[20]:
tailnum year type manufacturer model engines seats speed engine
0 N10156 2004.0 Fixed wing multi engine EMBRAER EMB-145XR 2 55 NaN Turbo-fan
1 N102UW 1998.0 Fixed wing multi engine AIRBUS INDUSTRIE A320-214 2 182 NaN Turbo-fan
2 N103US 1999.0 Fixed wing multi engine AIRBUS INDUSTRIE A320-214 2 182 NaN Turbo-fan
  • Say we want to create a variable indicating whether or not a plane is "large"
  • We could use a logical test and np.where() to do so
In [21]:
planes_df['large'] = np.where(planes_df['seats'] > 150, 'Yes', 'No')
In [22]:
planes_df[['seats', 'large']].head(3)
Out[22]:
seats large
0 55 No
1 182 Yes
2 182 Yes
  • Note that the first parameter is the vectorized test, the second parameter is the returned value if True, and the third parameter is the returned value if False

Your Turn¶

  1. Describe what this statement is doing.

    planes_df['modern'] = np.where(planes_df['year'] > 2008, 'Yes', 'No')
    
  2. Create a variable large_and_modern in planes_df to indicate whether a plane is large and modern using np.where().

Questions¶

Are there any questions before we move on?