Control Flow#
Learning Objectives#
- Execute code in a Jupyter notebook running in JupyterLab.
- Define control flow and explain why a computer program is similar to a cooking recipe.
- Explain what a while loop is and how it works.
- Given an objective, write logic in pseudocode that can be implemented with a while loop.
- Write a while loop in Python, with correct syntax, that that implements some given logic.
- Explain what a for loop is and how it works.
- Given an objective, write logic in pseudocode that can be implemented with a for loop.
- Write a for loop in Python, with correct syntax, that implements some given logic.
- Use a range object in a for loop.
- Explain the difference between while and for loops, and explain when one is more appropriate than the other.
- Explain what an if statement is and how it works.
- Given an objective, write logic in pseudocode that can be implemented with an if-elif-else statement.
- Given an objective, write logic in pseudocode that can be implemented with nested if statements.
- Write Python code, with correct syntax, that contains if, elif, and else clauses that implements some given logic.
What is Control Flow?#
Control flow is the order in which statements are executed in a program. In this section, you will learn about basic control flow, which consists of loops (while
and for
) and if-else
statements. Let’s begin with loops.
Loops#
A loop is a way of telling the computer to execute an action while a condition is met, then terminate. In this section, you will learn about while
loops and for
loops.
while
loops#
As its name suggests, a while
loop executes while a condition is true. In Python the loop first checks whether a condition is true. If yes, it takes some actions and then checks the condition again. If the condition is false, the loop terminates. If the condition is true, the loop takes the actions again. This repeats until the condition is false. The “actions” are called the body of the loop.
Following is an example of a simple while
loop in Python. The following code will compute the sum of the numbers from 1 to n, i.e. \(1+2+3 + \ldots + n\). Or if you want to get fancy, \(\sum_{i=1}^{n} i\).
Note: the following is a “code cell”. Below the code is the output that would result if you ran this code.
Note: This textbook is static: you cannot run the code. If you wish to run the code, copy and paste it into a Jupyter notebook on your computer. Alternatively, you can download this entire notebook and open that on your computer.
n = 5
result = 0
while (n > 0):
result = result + n
n = n - 1
print(f'The sum is {result}.')
The sum is 15.
There is a lot going on in the above code cell.
First, we created two variables,
n
andresult
, and initialized them to 5 and 0, respectively. We will teach you more about variables in a later notebook.Then we ran a
while
loop, which did the following:Checked whether \(n\) was greater than zero.
If yes, run the body of the loop and then check the condition again.
If no, terminate the loop.
The body of the loop consisted of two statements:
add the current value of \(n\) to the current value of
result
.decrease \(n\) by 1.
Checked the condition again. If true, repeat the body of the loop and check the condition again. If false, terminate the loop.
Notice that the final print statement is not executed until the loop has terminated.
Syntax of a while
loop#
In programming, syntax means the rules that the programming language follows. In Python, the syntax of a while
loop is:
while condition:
statement 1
statement 2
...
When you write a while
loop, it will always look like the above. If you deviate from the above, you will get an error. You must first type the word while
and then a condition (in the example above, the condition was n > 0
). The condition must be followed by a colon. The lines that follow the colon constitute the body of the while loop. These lines must be indented. The indentation tells Python which statements are part of the while loop. You can indent by using the TAB
key on your keyboard.
Some common errors when using while
loops#
The loop runs forever#
If you try to execute the following code, you will have a problem:
x = 7
while x > 5:
print('hello')
This loop will run forever! Since x
is 7, Python will run the body of the loop and print “hello”. It will then check x
again, find that it’s greater than 5, and print “hello” again. This will continue forever!
When writing a loop, you need to think about whether the loop will ever terminate.
You forget the colon#
In the following code cell, notice the missing colon after the condition (x > 0)
. Because the colon is missing, Python complains that the syntax is invalid.
x = 7
while (x > 0)
print(f'x is {x}')
x = x - 1
Cell In[2], line 3
while (x > 0)
^
SyntaxError: expected ':'
You forget to indent the body of the loop#
In the following code cell, notice the two statements in the body of the loop are not indented. When we executed this code, we received an indentation error. Python expects the line following a colon to be indented. Since it isn’t, an error results.
x = 7
while (x > 0):
print(f'x is {x}')
x = x - 1
Cell In[3], line 4
print(f'x is {x}')
^
IndentationError: expected an indented block after 'while' statement on line 3
SUMMARY OF WHILE LOOPS#
A while loop tests for a condition. If the condition is true, the body of the loop executes and the condition is tested again. This continues until the condition is false.
The syntax of a while loop is shown below. The colon and the indentation are mandatory.
while condition:
statement 1
statement 2
...
for
loops#
A for
loop is very similar to a while loop. It will test for a condition and execute the body of the loop if the condition is satisfied. The difference is that a for
loop will iterate, or loop over, something automatically. In other words, a for
loop is a while
loop but with some conveniences built in.
Let’s work through three examples of a for
loop. Before we do, let’s introduce something called a list. We will discuss lists at length later in this unit. For now, just know that a list is a collection of things. Some sample lists are [1,3,5,7,9]
and ['Indian food', 'Thai food', 'Bar food']
.
Syntax of a for
loop#
In programming, syntax means the rules that the programming language follows. In Python, the syntax of a for
loop is:
for variable in something_iterable:
statement 1
statement 2
...
When you write a for
loop, it will always look like the above. If you deviate from the above, you will get an error. You must first type the word for
and then a variable name. We will tell you about valid variable names in the next section. For now, just use letters or words with no spaces. The variable name must be followed the word in
. After the word in
, you must provide something that can be iterated, like a list or a range object. The iterable thing must be followed by a colon. The lines that follow the colon constitute the body of the for loop. These lines must be indented. The indentation tells Python which statements are part of the while loop. You can indent by using the TAB
key on your keyboard.
Example 1: Printing everything in a list#
myList = [1,2,3,7]
for x in myList:
print(x)
1
2
3
7
The code above creates a list called myList
. This list has four values, 1, 2, 3, and 7. The for
loop iterates over the list. It does so by automatically creating a new variable that I named x
. It sets x
to the first thing in the list, which in this case is 1. It then executes the body of the loop, which prints x. It then sets x
to the next thing on the list, 2, and executes the body of the loop. This continues until it has iterated over every value in the list.
You could replicate the above code using a while
loop, but it requires more work. To demonstrate this, we will replicate the previous for
loop using a while
loop in the code cell below. This code may be unclear to you because we have not yet taught you all of the concepts we are using.
myList = [1,2,3,7]
# The following line of code creates a variable
# that stores the length of myList
length_of_mylist = len(myList)
i = 0
while (i < length_of_mylist):
print(myList[i])
i = i + 1
1
2
3
7
Just like the for
loop, the above code cell prints every element of the list. However, we had to create more machinery to iterate over the list. We had to keep track of the list length by using a variable called list_of_mylength
. We also had to keep track of our current position in the list by using a variable i
. Finally, we had to add 1 to i
every time we executed the body of the loop. What a pain in the you-know-what!
The point here is that a for
loop takes care of a lot of this behind the scenes. This makes your job easier and decreases the likelihood that you make a mistake in your code.
Example 2: Adding everything in a list#
myList = [1,2,3,7]
mySum = 0
for x in myList:
mySum = mySum + x
print(f'The sum of the numbers in {myList} is {mySum}.')
The sum of the numbers in [1, 2, 3, 7] is 13.
This code is similar to the code in example 1. In addition, it creates a new variable called mySum
and initializes it to zero. During each iteration of the loop, it adds an element of the list to mySum
. After the loop terminates, the code prints the value of mySum
.
Example 3: Range objects#
for x in range(7):
print(x)
0
1
2
3
4
5
6
Here, we used a built-in Python function called range
. The range
function returns a sequence. In the above example, it returned the sequence 0, 1, 2, 3, 4, 5, 6
. The for
loop iterated over this sequence and printed every value in the sequence. The range
function is useful for when you want to do something a certain number of times.
In Python, and in many programming languages, sequences begin at 0 and end at \(n-1\). Notice that in the code above, range(7)
returns \(0, 1, 2, 3, 4, 5, 6\). This is by design, but is not natural for people new to programming. If you’re curious why this is, feel free to ask us outside of class, or check out the optional paragraph in the Unit 1-9 notebook, section 9.1.2.2 Retrieving a Single List Element.
If you want to start at 1, you can use something like range(1,5)
. This will return \(1, 2, 3, 4\).
Some common errors when using for
loops#
You use bad arguments in the range
function and get an empty sequence#
Remember that range(n)
will give the sequence \(0, 1, \ldots, n-1\). It begins at 0 and ends at one less than the argument \(n\). Also, remember that \(range(k, n)\) will give the sequence \(k, k+1, \ldots, n-1\). If you forget this behavior of the range
function, you will be surprised at your result.
Another common error is that the ending value of range is less than or equal to the starting value. For example:
for x in range(5,5):
print(x)
That code will not print anything because it wants to start at 5 and end at 4. That’s not possible, so the loop never executes.
Similarly, imagine the following:
k = 7
# Some code...
n = 4
for x in range(k, n):
print(x)
When you write a lot of code, you sometimes forget what you did earlier in your code. You end up with range(7,4)
. It can’t go from 7 to 3, so it never executes.
SUMMARY OF FOR LOOPS#
A for loop iterates over something. For each value of something, it executes some statements.
The syntax of a
for
loop is shown below. The colon, the wordin
, and the indentation are mandatory.variable
can be any valid variable name. We will discuss variables later in this unit.
for variable in something_terable:
statement 1
statement 2
...
if-else
statements#
When many people think of programming, they think of if
statements. if
statements are the heart of logic. Instructions given to another person, or to a computer, often depend on a condition. For example, say you are writing a grocery shopping list to give to someone else. You want raspberries, but only if they look delicious and are not too expensive. You could write the raspberry portion of your shopping list as:
if (raspberries look good) and (raspberry price < $4.00):
buy raspberries
else:
don't buy raspberries
Notice that we have two conditions. The raspberries must be attractive and they must be cheap. We join these two conditions using the word and
. We could also use the word or
, but that would change the logic. Joining the conditions with an or
, as we do below, would instruct your personal shopper to buy raspberries if they are good-looking or if they are cheap. With an or
, you would only forgo raspberries if they are bad-looking and expensive.
if (raspberries look good) or (raspberry price < $4.00):
buy raspberries
else:
don't buy raspberries
We can make this even more complicated. Say that blueberries are your second choice, but you only want good-looking blueberries that aren’t too expensive. And say that your third choice is apples, and you don’t care whether the apples look good or are pricey. You could modify your shopping list as follows:
if (raspberries look good) and (raspberry price < $4.00):
buy raspberries
else:
if (blueberries look good) and (blueberry price < $4.00):
buy blueberries
else:
buy apples
See how we can represent instructions? Also notice that the second if
statement is nested inside the first one. The second if
statement only matters if we’re not going to buy raspberries.
Guess what? You just learned how to use if
statements in Python! The syntax is similar to that for a while
loop. You begin with the word if
and follow it with a condition and then a colon. If the condition is true, the statements following the if
are executed.
An alternative to nesting if
statements is to use the elif
and else
clauses (elif
means “else if”). A generic if
statement looks like this:
if condition_A:
A statements
elif condition_B:
B statements
elif condition_C:
C statements
else:
else_statements
When Python sees something like this, it does the following. It checks condition_A. If that is true, it executes the A statements and then stops. It will not check any of the other conditions. However, if condition_A is false, it immediately checks condition_B. If that is true, it executes the B statements and then stops. If none of the conditions are true, Python will execute the else_statements and then stop. Think of the else as a residual.
Finally, note that the elif
and else
clauses are optional.
if
Statement Example 1, if
by itself.#
win_percentage = 0.75
if (win_percentage > 0.5):
print('Team is good.')
Team is good.
This example tells us whether a team is any good, given its record. However, if the team’s win percentage is less than 50%, the code will not print anything. Let’s fix that in the next example.
if
Statement: Example 2, if-else#
win_percentage = 0.25
if (win_percentage > 0.5):
print('Team is good.')
else:
print('Team sucks.')
Team sucks.
if
Statement: Example 3, if-elif-else#
In this example, let’s classify a person based on their age.
age = 43
if (age < 13):
print('child')
elif (age < 20):
print('teenager')
elif (age < 30):
print('young adult')
elif (age < 50):
print('middle aged')
else:
print('old')
middle aged
Let’s ensure that you understand how the code above works.
First, the
input
function asks for your age. You type in something and Python converts it to a number using theint
function. It stores the result in the variableage
.The program then checks whether
age
is less than 13. If yes, it prints ‘child’ and stops. None of the remaining code is executed.If age is not less than 13, it checks whether the age is less than 20. If yes, it prints ‘teenager’ and stops. Thus, ‘teenager’ is printed for all ages between 13 and 19.
This process continues. If age is 50 or higher, the code prints ‘old’ and stops.
Notice that the above code creates buckets, or ranges, for ages. For example, a teenager is someone whose age is between 13 and 19, even though the condition for teenager is (age < 20)
. Why? Because if the age is less than 13, the program will print ‘child’ and stop. It will only test (age < 20)
if it has already found that age is not less than 13.
if
Statement: Example 4, nested if statements#
As we saw earlier with the grocery list example, it is possible to have an if
statement inside another if
statement. For example, we could modify the code above to distinguish between young children and older children.
age = 11
if (age < 13):
print('Pre-teen:')
if (age < 4):
print('baby')
else:
print('older child')
elif (age < 20):
print('teenager')
else:
print('adult')
Pre-teen:
older child
In the above, if the age is less than 13, the program prints ‘Pre-teen’. The program then checks whether the person is really young. If yes, they are labelled a baby. If no, they are labelled an older child.
You may be wondering when to use nested if
statements and when to use an elif
. Good question! Generally speaking, use elif
when you have a set of conditions that do not overlap. If you have a condition that requires further testing, then it makes sense to use a nested if
.
It is often possible to implement the same logic in multiple ways. When in doubt, do it in the simplest, clearest way.
Some common errors#
Many of the common errors for while
loops also occur with if
statements. These are:
The condition does not evaluate to true or false (or it does, but not in a way that you expected).
You forget a colon.
You forget to indent the body of the loop.
See the documentation above for while
loops for a description of these errors.
Another Common Error: Your logic does not make sense#
Another common issue with if
statements is that your logic does not make sense. For example, consider this code:
age = 10
if (age < 10):
print('child')
elif (age >= 18):
print('adult')
The problem with this code is that it does nothing for some valid ages. If age is between 10 and 17, the code will print nothing. This is probably not what you want.
Here’s another example:
age = 9
if (age < 18):
print('minor')
if (age >= 18):
print('adult')
This code will never print the word ‘adult’. It simply cannot. The statement if (age >= 18)
is only executed if age is less than 18. Thus, it can never be true.
Our recommendation is that you think of all possible outcomes before you write your if
statement. Use that to design your if
statement. Finally, after you have written your code, test it!
SUMMARY OF IF STATEMENTS#
An if
statement tests a condition and executes some statements if the condition is true. If the condition is not true, optional elif
and else
statements can be used to refine the tests.
The syntax of an if
statement is:
if condition_A:
A statements
elif condition_B:
B statements
elif condition_C:
C statements
else:
else_statements
Summary of Control Flow#
Control flow is a way of expressing ideas and logic through computer code. It is analogous to a recipe in cooking. Through control flow, we can write out a sequence of steps that we want the computer to take. Those steps can vary based on certain conditions that we specify.
In this module, you learned about some basic control flows: while
loops, for
loops, and if
statements. The ideas learned in this module are the basis of much of data analytics. You will use these ideas again and again, even if you work in Excel or Tableau.