Pre-MAP Course Website | Pre-MAP GitHub | Google

Control flow

There are a few basic types of control flow statements that we will learn. These are as follows:

  • if: do something if some condition is True
  • for: do something repeatedly for some number of times, or on some number of items
  • while: do something while some condition is True

Let's look at some examples. Notice that identation (whitespace preceding code) matters in Python! Blocks of text following a for, while or if statement must be indented to run properly.

The if statement

When you need a program to do something more complicated than arithmetic, you'll sometimes need the code to do something if some condition is met, otherwise it should do something else.

One basic example is checking a password. If someone submits the right password, then tell them they're welcome, else (otherwise) give them a warning to get away. Here's how we can do that in Python:

password = 'lemon drop'

if password == 'lemon drop':
    # This indented code will only run if the above condition is True
    print('You are welcome here.')
else:
    # This indented code will only run if the above condition is False
    print('Get away!')

Copy and paste this code into the cell below, and check that it works for various values of password.


In [ ]:

The above example has only two possible outcomes - either the password is correct or incorrect. Sometimes, you'll want more possible outcomes, and for those occasions you can use the elif statement, meaning "else-if". For example, let's create a program that tells a first-year student how ready they are for a course by the course number:

course_number = 192

if course_number < 200:
    print("This course is going to be fun")
elif course_number < 300:
    print("This course is going to be hard")
elif course_number < 400: 
    print("You might want to wait for this course")
else:
    print("Run away!")

Copy and paste this code into the cell below and explore the possible outputs with various inputs for course_number.


In [ ]:

Example 1

In the cell below, explain the sequence of events in the code starting from the first line, when course_number = 601, in comments:


In [ ]:

Example 2

In the cell below, create a program that checks that the user paid the correct amount for a product. You should make two variables, customer_paid for how much the customer gave you, and price for how much the produce costs. Then your program will do one of three things:

  1. If the customer pays exactly the price, print "thanks!"
  2. If the customer pays more than the price, print "thanks!!!"
  3. If the customer pays less than the price, print "try again"

In [ ]:

Example 3

Since Python is named for the comics Monty Python, in the cell below, you will write code inspired by Monty Python and the Holy Grail. Watch this short clip from the film, then read on...

Write a program which checks if the user has counted to the correct number, and give the user responses appropriate for the number submitted.


In [ ]:

The while loop

The while command is the first type of loop we'll use. A loop is a snippet of code that gets run repeatedly. Let's see an example below, where we use a while loop to add 1 to number for as many times as necessary until number is greater than or equal to 10:

number = 0

while number < 10:
    print(number)
    number += 1

Copy and paste the code from above into the cell below. What gets printed and why?


In [ ]:

Example 4

Using the example above as a template, create a variable counter = 5000, and use a while loop to subtract 10 from counter until counter is less than -5000.

Print counter after the loop is complete, so you can see the result.


In [ ]:


It's possible to accidentally create a loop that has no end. For example, if you wrote the above loop like this,

counter = 5000

while counter < 6000:
    counter -= 10

the counter will always be less than 6000, so the condition counter < 6000 will always be True, and the loop will never end. That's called an infinite loop. If you create an infinite loop, the program will keep running forever, unless you kill it. You can kill a Python cell in an iPython Notebook by pressing the Stop button in the toolbar at the top of the page.

Example 5

In this example, we'll create an infinite loop that doesn't go on forever, because it terminates with a break statement.

Let's start a counter at 10, and iteratively subtract one from counter. We could make the while loop terminate when counter == 1 by writing the loop like this

counter = 10

while counter > 1:
    counter -=1

print(counter)

Or, we could break out of an infinite loop:

counter = 10

# This loop is infinite on purpose:
while True:
    counter -= 1

    # When counter is equal to one, break out of the loop:
    if counter == 1:
        break

print(counter)

Example 6

  1. Copy and paste the loop with the break from above into the cell below, and check that it works.

  2. Modify the loop so that it terminates when the counter is at negative one million (reminder: you can use e for scientific notation)

  3. Now modify the loop so that it counts down from 10 to negative one million by twos.


In [ ]:

The for loop

The for loop is trickier to learn than the other statements we've learned so far, but it's worth the trouble!

Let's say you have a list of the names, and a list of the orbital periods of the solar system planets that you want to work on. Let's print them:

planet_names = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Pluto']

# Orbital periods in units of years:
orbital_periods = [0.24, 0.62, 1.0, 1.88, 11.86, 29.46, 84.01, 164.8, 247.7]

print(planet_names, orbital_periods)

Copy and paste this into the cell below to inspect the output:


In [ ]:

Note that the lists are printed sequentially. It would be a lot easier to read this like a table, with a column of planet names, and a column of orbital periods. We could get a table-like output by printing with a for loop.

Let's start by printing each name in the planet_names list with a for loop:

for name in planet_names:
    print(name)

Let's break it down. planet_names is the list that we're going to iterate over, or loop over. When you say for name in planet_names, here's what happens:

  • the for says you're going to start a for loop
  • name is a new variable that you're specifying, which the for loop is going to give values to
  • in says that each name is going to come from an element of the planet_names list
  • planet_names is the list that you're going to pull elements from

Here's what is going to happen when the for loop is run:

  1. The for loop sets the variable name equal to the first item in planet_names (which is "Mercury")
  2. The indented code is executed
  3. The for loop sets name equal to the second item in planet_names (which is "Venus")
  4. The indented code is executed
  5. The for loop sets name equal to the third item in planet_names (which is "Earth")
  6. ...

You could write code that gives you the same output, but it would be really redundant:

name = planet_names[0]
print(name)

name = planet_names[1]
print(name)

name = planet_names[2]
print(name)
...

Example 7

In the cell below, use the for loop above as a template to create a for loop that prints the orbital period of each planet.


In [ ]:

Now we're going to use a new function called range, which is useful in for loops.

Copy and paste this example into the cell below and look at the output:

for i in range(5):
    print(i)

In [ ]:

The for loop is first setting i=0, then i=1, then i=2, etc. The range function is producing a series of consecutive integers just like np.arange did. The argument 5 tells range to produce the numbers from zero to four.

Now, let's recall how indexing of lists works. If we want to see the first element of the planet_names list we would write planet_names[0], or planet_names[1] for the second element of the list. In order to print out each element of the list one at a time, we could write something like this:

i = 0
print(planet_names[i])

i = 1
print(planet_names[i])

i = 2
print(planet_names[i])
...

or we could let the for loop do it for us without repeating any code like this:

number_of_planets = len(planet_names)

for i in range(number_of_planets):
    print(planet_names[i])

This loop will do the same thing as the longer code that we wrote above, but we only had to write the print statement line one time.

Note that we had to figure out the length of the planet_names list in order to figure out at which number range should end.

Example 8

Copy and paste the last for loop above into the cell below, and inspect its output.

Modify the code so that now it prints each planet name one at a time, and each orbital period.

Heads up: this is the toughest coding we've done so far, and it's going to be confusing. Nobody understands for loops the first time that they see them, so don't hesitate to ask for help. Remember to talk with your neighbors, and to raise your hand if you get stuck!


In [ ]:

Example 9

for loops are mostly useful for doing repeated calculations on items of a list. In the cell below, make a for loop that prints the number of letters in each planet name.

Hint: The len (length) function works on strings in the same way that it does on lists.


In [ ]:

So far, we've seen examples where we wanted to get elements out of a list, but we also use for loops to add elements to lists. Let's make a list of the number of letters in each planet name. We could do that without a for loop like this:

# Start with an empty list: 
letters_per_name = []

letters_per_name.append(len(planet_names[0]))

letters_per_name.append(len(planet_names[1]))

letters_per_name.append(len(planet_names[2]))
...

Example 10

In the cell below, create an empty list called letters_per_name, then using a for loop, append to it the number of letters in each planet name. Print the completed list.


In [ ]:

Combining control flow statements

Now let's build on the previous example. Copy and paste the code from the previous cell into the cell below.

Example 11

This time, let's only append the letters per name to the list, if the number of letters is even. Print the result to check if it worked.

Recall: if a number is even, the modulus of that number and two is zero, for example 8 % 2 == 0


In [ ]:

Example 12

Copy and paste the code in the cell above into the cell below. Modify it to print out the names of the planets with even numbers of letters greater than four letters long. Check that it works successfully.

Hint: You might need two if statements


In [ ]:


In [ ]:


In [ ]: