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

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
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 [3]:
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 has a particular value¶

All our examples thus far fall into this category:

In [4]:
x = 7

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

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

Something exists in a container¶

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

In [6]:
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 type of object¶

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

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

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

All or some of something meets a condition¶

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

In [10]:
email_is_spam = [False, False, True]
In [11]:
# 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!

There's a lot of flexibility!

Questions¶

Are there any questions before we move on?