Python Basics 2#

Description: This lesson describes the basics of flow control statements including:

Completion Time: 90 minutes

Python Libraries Used:

Additional materials


Flow Control Statements#

In Python Basics 1, you learned about expressions, operators, variables, and a few native Python functions. We wrote programs that executed line-by-line, starting at the top and running to the bottom. This approach works great for simple programs that may execute a few tasks, but as you begin writing programs that can do multiple tasks you’ll need a way for your programs to decide which action comes next. We can control when (or if) code gets executed with flow control statements. If a program is a set of steps for accomplishing a task, then flow control statements help the program decide the next action.

Flow control statements work like a flowchart. For example, let’s say your goal is to hang out and relax with friends. There are a number of steps you might take, depending on whether your friends are available or you feel like making some new friends.

Flowchart to hangout with friends

Each diamond in our flowchart represents a decision that has to be made about the best step to take next. This is the essence of flow control statements. They help a program decide what the next step should be given the current circumstances.

Boolean Values#

One way we to create flow control statements is with boolean values that have two possible values: True or False. In our example above, we could consider a “Yes” to be “True” and a “No” to be “False.” When we have the data we need to answer each question, we could store that answer in a variable, like:

  • are_friends_available = False

  • make_new_friends = True

  • new_friend_available = True

This would allow us to determine which action to take next. When we assign boolean values to a variable, the first letter must be capitalized:

# Note, the first letter of a boolean value must always be capitalized in Python
are_friends_available = false
print(are_friends_available)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[1], line 2
      1 # Note, the first letter of a boolean value must always be capitalized in Python
----> 2 are_friends_available = false
      3 print(are_friends_available)

NameError: name 'false' is not defined
# The boolean values **True** and **False** cannot be used for variable names. 
# Treating the boolean value True as a variable will create an error
True = 7
# But we can store Boolean values in a variable

futbol_is_life = False
tacos_are_life = True

Comparison Operators#

Now that we have a way to store integers, floats, strings, and boolean values in variables, we can use a comparison operator to help make decisions based on those values. We used the comparison operator == in Python Basics 1. This operator asks whether two expressionsare equal to each other.

# Comparing two values with the comparison operator ==
67 == 67
# Note, a comparison operator uses ==
# Do not confuse with variable assignment statement which uses a single =
67 = 67

There are additional comparison operators that can help us with flow control statements.

Operator

Meaning

==

Equal to

!=

Not equal to

<

Less than

>

Greater than

<=

Less than or equal to

>=

Greater than or equal to

# Use the "Not equal to" operator
# Use the "equal to" operator with a string

A string cannot be equal to a float or an integer.

# Try using the "equal to" operator to compare a string with an integer

But an integer can be equal to a float.

# Try using the "equal to" operator to compare an integer with a float

We can use the comparison operator with variables.

# Using a comparison operator on a variable
# Create a variable number_of_dogs and assign the value of zero


# Check whether number_of_dogs is greater than or equal to 1

Boolean Operators (and/or/not)#

We can also use Boolean operators) (and/or/not) to create expressions that evaluate to a single Boolean value (True/False).

Using the Boolean Operator and#

The and operator determines whether both conditions are True.

# If condition one is True AND condition two is True
# What will the evaluation be?
True and True
# If condition one is True AND condition two is False
# What will the evaluation be?
True and False

In order for an and expression to evaluate to True, every condition must be True. Here is the “Truth Table” for every pair:

Expression

Evaluation

True and True

True

True and False

False

False and True

False

False and False

False

Since and expressions require all conditions to be True, they can easily result in False evaluations.

Using the Boolean Operator or#

The or operator determines whether any condition is True.

# Is expression one True OR is expression two True?
True or False
# Is condition one True OR is condition two True?
False or False

An or expression evaluates to True if any condition is True. Here is the “Truth Table” for every pair:

Expression

Evaluation

True or True

True

True or False

True

False or True

True

False or False

False

Since or expressions only require a single condition to be True, they can easily result in True evaluations.

Using the Boolean Operator not#

Thenot operator only operates on a single expression, essentially flipping True to False or False to True.

# The not operator flips a True to False
not False

Combining Boolean and Comparison Operators#

We can combine Boolean operators and comparison operators to create even more nuanced Truth tests.

# Evaluating two conditions with integers at once
(3 < 22) and (60 == 34) # What does each condition evaluate to?
# Evaluating two conditions with integers at once
(3 == 45) or (3 != 7) # What does each condition evaluate to?

So far, we have evaluated one or two conditions at once, but we could compare even more at once. (In practice, this is rare since it creates code that can be difficult to read.) Boolean operators also have an order of operations like mathematical operators. They resolve in the order of not, and, then or.

Writing a Flow Control Statement#

The general form of a flow control statement in Python is a condition followed by an action clause:

In this condition:
       perform this action

Let’s return to part of our flowchart for hanging out with friends.

Flowchart showing if homework is yes then do assignment

We can imagine a flow control statement that would look something like:

if have_homework == True:
        complete assignment

The condition is given followed by a colon (:). The action clause then follows on the next line, indented into a code block.

  • If the condition is fulfilled (evaluates to True), the action clause in the block of code is executed.

  • If the condition is not fulfilled (evaluates to False), the action clause in the block of code is skipped over.

Code Blocks#

A code block is a snippet of code that begins with an indentation. A code block can be a single line or many lines long. Blocks can contain other blocks forming a hierarchal structure. In such a case, the second block is indented an additional degree. Any given block ends when the number of indentations in the current line is less than the number that started the block.

Visualization of code block indentations

Since the level of indentation describes which code block will be executed, improper indentations will make your code crash. When using indentations to create code blocks, look carefully to make sure you are working in the code block you intend. Each indentation for a code block is created by pressing the tab key.

Types of Flow Control Statements#

The code example above uses an if statement, but there are other kinds of flow control statements available in Python.

Statement

Means

Condition for execution

if

if

if the condition is fulfilled

elif

else if

if no previous conditions were met and this condition is met

else

else

if no condition is met (no condition is supplied for an else statement)

while

while

while condition is true

for

for

execute in a loop for this many times

try

try

try this and run the except code if an error occurs

Let’s take a look at each of these flow control statement types.

if Statements#

An if statement begins with an expression that evaluates to True or False.

  • if True, then perform this action

  • if False, skip over this action

In practice, the form looks like this:

if this is True:
        perform this action

Let’s put an if statement into practice with a very simple program that asks the user how their day is going and then responds. We can visualize the flow of the program in a flowchart.

Flowchart of a good day program

Our program will use a single if statement. If the user types “Yes” or “yes”, then our program will send a response.

# A program that responds to a user having a good day
having_good_day = input('Are you having a good day? (Yes or No) ') # Define a variable having_good_day to hold the user's input in a string

if having_good_day == 'Yes' or having_good_day == 'yes':  # If the user has input the string 'Yes' or 'yes'
    print('Glad to hear your day is going well!') # Print: Glad to hear your day is going well!

Our program works fairly well so long as the user inputs ‘Yes’ or ‘yes’. If they type ‘no’ or something else, it simply ends. If we want to have our program still respond, we can use an else statement.

else Statements#

An else statement does not require a condition to evaluate to True or False. It simply executes when none of the previous conditions are met. The form looks like this:

else:
        perform this action

Our updated flowchart now contains a second branch for our program.

The program flowchart with two branches

# A program that responds to whether the user is having a good or bad day
having_good_day = input('Are you having a good day? (Yes or No) ') # Define a variable having_good_day to hold the user's input

if having_good_day == 'Yes' or having_good_day == 'yes': # If the user has input the string 'Yes' or 'yes'
    print('Glad to hear your day is going well!') # Print: Glad to hear your day is going well!
    
# Write an else statement here

Our new program is more robust. The new else statement still gives the user a response if they do not respond “Yes” or “yes”. But what if we wanted to add an option for when a user says “No”? Or when a user inputs something besides “Yes” or “No”? We could use a series of elif statements.

elif Statements#

An elif statement, short for “else if,” allows us to create a list of possible conditions where one (and only one) action will be executed. elif statements come after an initial if statement and before an else statement:

if condition A is True:
        perform action A
elif condition B is True:
        perform action B
elif condition C is True:
        perform action C
elif condition D is True:
        perform action D
else:
       perform action E

For example, we could add an elif statement to our program so it responds to both “Yes” and “No” with unique answers. We could then add an else statement that responds to any user input that is not “Yes” or “No”.

Flowchart showing three branches

# A program that responds to whether the user is having a good or bad day
having_good_day = input('Are you having a good day? (Yes or No) ') # Define a variable having_good_day to hold the user's input

if having_good_day == 'Yes' or having_good_day == 'yes': # If the user has input the string 'Yes' or 'yes'
    print('Glad to hear your day is going well!') # Print: Glad to hear your day is going well!

# Write an elif statement for having_good_day == 'No'


# An else statement that catches if the answer is not 'yes' or 'no'
else: # Execute this if none of the other branches executes
    print('Sorry, I only understand "Yes" or "No"') # Note that we can use double quotations in our string because it begins and ends with single quotes

The difference betweenelif and if?#

When an elif condition is met, all other elif statements are skipped over. This means that one (and only one) flow control statement is executed when using elif statements. The fact that only one elif statement is executed is important because it may be possible for multiple flow control statements to evaluate to True. A series of elif statements evaluates from top-to-bottom, only executing the first elif statement whose condition evaluates to True. The rest of the elif statements are skipped over (whether they are True or False).

In practice, a set of mutually exclusive if statements will result in the same actions as an if statement followed by elif statements. There are a few good reasons, however, to use elif statements:

  1. A series of elif statements helps someone reading your code understand that a single flow control choice is being made.

  2. Using elif statements will make your program run faster since other conditional statements are skipped after the first evaluates to True. Otherwise, every if statement has to be evaluated before the program moves to the next step.

  3. Writing a mutually exclusive set of if statements can be very complex.

In the previous code cell, try changing the elif to an if. Then answer the question with a “Yes.” You’ll receive two responses! Why do you think that is?

while Loop Statements#

So far, we have used flow control statements like decision-making branches to decide what action should be taken next. Sometimes, however, we want a particular action to loop (or repeat) until some condition is met. We can accomplish this with a while loop statement that takes the form:

while condition is True:
       take this action

After the code block is executed, the program loops back to check and see if the while loop condition has changed from True to False. The code block stops looping when the condition becomes False.

In the following program, the user will guess a number until they get it correct.

flowchart for number-guessing program

# A program that asks the user to guess a number

# The secret number is set here by the programmer.
secret_number = str(4) # We convert the integer to a string to compare easily with a user input string

# Ask the user to make a guess and take input in a string
guess = input('I am thinking of a number between 1 and 10. Can you guess it? ') # Take the user's first guess

# Check to see if the user guess matches our secret number
while guess != secret_number: # While the users guess does not equal secret_number
    guess = input('Nope. Guess again! ') # Allow the user to change the value of guess

print('You guessed the secret number, ' + secret_number) # Print a congratulations message with the secret number

Stopping Accidental Infinite Loops#

When using a while loop, it is possible to accidentally create an infinite loop that never ends. This happens because the while condition never becomes False.

If you accidentally write code that infinitely repeats, you can stop the execution by selecting Interrupt from the Kernel menu. (Alternatively, you can press the letter i twice on your keyboard.) It is also a good idea to remove the output of the rogue cell. You can do this from the Edit menu.

  • Clearing output from a single cell: EditClear Cell Output

  • Clearing output from all cells: EditClear Outputs of All Cells

Clearing current outputs.

# Run this infinite loop then interrupt the kernel
from time import sleep # Importing the sleep module so we can slow down our infinite loop

while True:
    print('Oh noes!')
    sleep(1) # A one second pause so our infinite loop doesn't make the notebook gigantic!

If you didn’t already, try clearing the output from the infinite loop code cell!

A Repeating while Loop#

In the program above, the while loop checked to see if the user guessed a particular number. We could also use a while loop to repeat a code block a particular number of times.

# A loop program that prints out 0, 1, 2
i = 0 # A variable to help count how many loops have been completed

while i < 3:
    print(i)
    i = i + 1 # We can also write an equivalent shortcut: i += 1

for Loop Statements with a range() Function#

An abbreviated way to write a while loop that repeats a specified number of times is using a for loop with a range() function. This loop takes the form:

for i in range(j):
       take this action

where i is a generic variable for counting the number of iterations and j is the number of times you want the code block to repeat.

The starting value of i is 0. After each loop, i increases by one until it reaches j. The loop then stops. The variable names i and j are merely conventions. Using a different name may make the purpose of your code clearer to readers.

# A `for` loop that prints the value of the current iteration, here called `i`. 
for i in range(3):
    print(i)

Try your hand at a repeating loop. Write a program that prints “What?” five times.

# A `for` loop that repeats 'What?'

Try changing the variable name i to something else. What effect does that have on the program?

Continue and Break Statements#

while loops and for loops can also use continue and break statements to affect flow control.

  • A continue statement immediately restarts the loop.

  • A break statement immediately exits the loop.

Let’s return to our secret number guessing program. We will write the same program workflow using continue and break statements.

Flowchart for secret number guessing program

# A program that asks the user to guess a number

# Initialize the variables `guess` and `secret_number`
guess = 0
secret_number = str(4) # The secret number is set here by the programmer. Notice it is turned into a string so it can be easily compared with user inputs.

# Ask the user to make a guess
print('I am thinking of a number between 1 and 10.') 

# Test whether the user guess matches `secret_number`
while True:
    guess = input('What is your guess? ')
    if guess == secret_number:
        break
    else:
        continue
        
        
# After loop ends, print a congratulations message with the secret number       
print('You guessed the secret number, ' + secret_number) 

Exception Handling with try and except#

When running code that may create an error, we can use try and except statements to stop a program from crashing.

# Try running the first code block, if there's an error then run the `except` code

try:
    user_number = input('Please enter a whole number: ')
    user_number = int(user_number)
    print('Thank you for entering a whole number.')

except:
    print('That is not a whole number.')

Coding Challenge! < / >

Using your knowledge of flow control statements, can you write a program that asks a user for their name, then prints out a response depending on whether they are old enough to drive? Check the end of this notebook for example solutions.


# Level 1 Challenge

# Ask the user for their name and store it in a variable `user_name`
# Ask the user for their age and store it in a variable `user_age`
# Write an if, elif, else statement that checks to see if the user is driving age.
# If the user is driving age, print out "user_name is old enough to drive."
# If the user is not driving age, print out "user_name is not old enough to drive."
# Level 2 Challenge

# Improve your flow control to consider whether the user has input a realistic age
# If the user inputs an age over 120, print "Is `user_name` a human or a turtle?"
# If the user inputs an age less than 5, print "`user_name` is not even ready for a bicycle!"
# Level 3 Challenge
# A program that checks to see if a user is old enough to drive.
# Verifies user has input a number and it is realistic.

# Find a solution to address when a user enters text that is not a number.
# Level 4 Challenge
# A program that checks to see if a user is old enough to drive.
# It checks to see whether the age entered is a valid number. 
# It also checks to see whether the age entered 
# is a realistic number (greater than 0 and less than 150)
# If the user enters an age that is not a number or unrealistic, it prompts for a new age

Attribution Creative Commons CC BY License

Created by Nathan Kelber and Ted Lawless for JSTOR Labs under Creative Commons CC BY License

Coding Challenge! Solutions#

There are often many ways to solve programming problems. Here are a few possible ways to solve the challenges, but there are certainly more!

  • See below for some solutions

# Level 1 Solution
# A program that checks to see if a user is old enough to drive.

# Ask the user for their name and store it in a variable `user_name`
# Ask the user for their age and store it in a variable `user_age`
# Write an if, elif, else statement that checks to see if the user is driving age.
# If the user is driving age, print out "user_name is old enough to drive."
# If the user is not driving age, print out "user_name is not old enough to drive."

user_name = input('What is your name? ')
user_age = int(input('And what is your age? '))

if user_age >= 16:
    print(f'{user_name} is old enough to drive.')
elif user_age < 16:
    print(f'{user_name} is not old enough to drive.')
# Level 2 Solution
# A program that checks to see if a user is old enough to drive.
# Now with improved ability to check if the age number is realistic.

# Improve your flow control to consider whether the user has input a realistic age
# If the user inputs an age over 120, print "Is `user_name` a human or a turtle?"
# If the user inputs an age less than 5, print "`user_name` is not even ready for a bicycle!"

user_name = input('What is your name? ')
user_age = int(input('And what is your age? '))

if user_age > 120:
    print(f'Is {user_name} a human or a turtle?')
elif user_age < 5:
    print(f'{user_name} is not even ready for a bicycle!')
elif user_age >= 16:
    print(f'{user_name} is old enough to drive.')
elif user_age < 16:
    print(f'{user_name} is not old enough to drive.')
# Level 3 Solution (using continue/break)
# A program that checks to see if a user is old enough to drive.
# Verifies user has input a number and it is realistic.

# Find a solution to address when a user enters text that is not a number.

user_name = input('What is your name? ')

while True:
    user_age = input('What is your age? ')
    try:
        user_age = int(user_age)
        if user_age > 120:
            print(f'Is {user_name} a human or a turtle?')
        elif user_age < 5:
            print(f'{user_name} is not even ready for a bicycle!')
        elif user_age >= 16:
            print(f'{user_name} is old enough to drive.')
        elif user_age < 16:
            print(f'{user_name} is not old enough to drive.')
        break
    except:
        print('Please input a number for your age.')
        continue
# Level 4 Challenge
# A program that checks to see if a user is old enough to drive.
# It checks to see whether the age entered is a valid number. 
# It also checks to see whether the age entered 
# is a realistic number (greater than 0 and less than 150)
# If the user enters an age that is not a number or unrealistic, it prompts for a new age

# Get user's age
user_name = input('What is your name? ')

# Check that age is a realistic number
while True:
    user_age = input('What is your age? ')
    try:
        user_age = int(user_age)
        if user_age < 120 and user_age > 0:
            break    
        print('Please input a realistic number for your age.')
        continue
    except:
        print('Please input an actual number for your age.')
        continue

# Respond to user's age      
if user_age >= 16:
    print(f'{user_name} is old enough to drive.')
elif user_age < 16:
    print(f'{user_name} is not old enough to drive.')

    

Attribution Creative Commons CC BY License

Created by Nathan Kelber and Ted Lawless for JSTOR Labs under Creative Commons CC BY License