Learn the Fundamentals of Control Flow in Python

Your Python scripts have to make decisions and control flow is the key.
Headshot of author Peter Grant
Peter Grant
Expert Columnist
July 15, 2021
Updated: July 21, 2021
Headshot of author Peter Grant
Peter Grant
Expert Columnist
July 15, 2021
Updated: July 21, 2021

Python is a favorite programming language among scientific and data science communities. The relatively easy to understand syntax, open nature of the community and availability of many useful packages make Python an attractive language to learn. As a result, many people (myself included) want to become experts in Python to improve our career opportunities. In order to become proficient in Python, we first have to learn control flow.

 

 What Is Control Flow?

First things first: control flow is how you instruct your programs to make decisions about which pieces of code to run. By default, programs compute each line of code sequentially, with no thought about how things are progressing.

Control Flow

In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated.

What if you don’t want to run every line of code? What if you have a few different solutions, and the code must decide which to use based on the conditions? What if you need the program to use the same code to do the same calculations repeatedly, with slightly different inputs? What if you want to run a few lines of code repeatedly until the program meets a particular condition? This is where control flow comes into play.

Control flow enables you to instruct your program on how to choose which sections of code to run and when.

There are several different forms of control flow but here we’ll look at the top three.

The Most Important Forms of Control Flow

  1. If-Then-Else
  2. For Loops
  3. While Loops

If-then-else statements instruct the program to choose between different blocks of code to run depending on the data passed to them and the specified conditional checks. For loops execute a specified number of times, and commonly pass a piece of data on which you want to execute the following code. Finally, while loops operate so long as a condition is met and are a good way to handle unpredictable data.

Learn More From Peter GrantWhat Is Multiple Regression?

 

1. If-Then-Else

The if-then-else statement is one of the most well known control flow statements in programming and it does pretty much exactly what it sounds like it will do. If can be broken down into a few logical statements.

  • if a condition is met

  • then execute this section of code

  • else (if the condition is not met) 

  • then execute this section of code

In other words, you can write programs that make decisions about which sections of code to execute, and can handle different situations accordingly. For example, you could think of this like a power button on any appliance. The button provides data on whether you want the machine to be on or off, and it can make control decisions accordingly. In this case the control flow would be:

  • if the power button is set to “on,”

  • then provide power to and operate the appliance

  • else the power button is not set to “on”

  • then do not apply power to or operate the appliance

In Python we do this by writing the logical check for the if statement, followed by a colon, and indenting the lines that need to be executed if the program meets the condition. Keep in mind that you can include as many lines of code within the if statement as you like so long as they’re all indented. Consider the following:

Condition = 'Yes'

if Condition == 'Yes':

   print('These lines are executed because Condition is 'Yes'')

   print('This line is also indented, and gets included')

   print('It can keep going like this for a LONG time')

The first line created a variable called Condition and set it to ‘Yes.’ This was simply so the code would have something for the if statement to check. The second line checked to see if Condition was equal to ‘Yes’ or not. Since it is, you can expect the following three lines of code to execute because they are all indented the same number of spaces. Python will execute every line until it finds a line that does not have the same indentation.

What if Condition isn’t ‘Yes’? Maybe there’s something you need the code to do under any and all situations except when Condition == ‘Yes.’ This is where the else statement comes into play. This informs Python of what to do when the preceding condition is not met and functions in the same way as the if statement. Note that if the condition isn’t met, Python will execute no code unless it has an else statement.

Here’s an example using an else statement:

Condition = 'Yes'

if Condition == 'Yes'':

   print('These lines are executed because Condition is 'Yes'')

   print('This line is also indented, and gets included')

   print('It can keep going like this for a LONG time')

else:

   print('This code gets executed when Condition is not 'Yes'')

Notice how we added the else statement after the code to be executed when Condition is ‘Yes.’ Now the program will perform the following steps:

  • Check to see if Condition equals ‘Yes.’

  • If it is, execute the three indented lines of print statements located between the if statement and the else statement.

  • If it is not true, the program proceeds to the else statement.

  • It will then execute the one indented print statement located after else.

You can also use multiple conditions in your code if there are a number of different situations to consider. You do that using an elif (else-if) statement. The program executes these lines if the previous if statements were false, but the data meets a new if condition. Consider the following example:

Condition = 'Maybe'

if Condition == 'Yes'':

   print('These lines are executed because Condition is 'Yes'')

   print('This line is also indented, and gets included')

   print('It can keep going like this for a LONG time')

elif Condition == 'Maybe':

   print('This line executes if 'Condition' is 'Maybe')

else:

   print('Print this when Condition is neither 'Yes' nor 'Maybe')

Notice I changed Condition to equal ‘Maybe.’ Now the first if statement is false, so the code doesn’t execute the following three lines. The first elif condition is true, so the code executes the line specified there. Finally, the data doesn't reach the else condition in this example, as it would only execute when Condition is neither ‘Yes’ or ‘Maybe.’

More Python ToolsHow to Create Report-Ready Plots in Python

 

2. For Loops

For loops execute a code a specified number of times, typically iterating over a collection of items. We often use them when we want to execute a certain line of code on every item in a list. Here’s an example:

List = [0, 1, 2, 3, 4, 5]

for i in List:

   List[i] = i**2

print(List)

This code works as follows:

  • First, it creates a list containing the numbers one through five and stores them in the variable List.

  • Second, it creates a for loop iterating through all items in List. This tells the code to grab the first item in List (in this case, zero), temporarily store it in the variable i, and perform the code within the for loop. When the program completes executing the code for the first item, it moves to the second item (in the example, one). This process repeats until the program executes the code for each of the items in List. In the example above, that means executing six times with the six different values in List.

  • Third, the program performs the calculations specified by the code. In this case that means squaring the value and storing it back in the list. The program changes each value stored in List so that, when the code is completed, it stores the square of the values that were originally in List.

  • Finally, the program prints List to the console.

What do you think the printed output will be? Go ahead and write the code to test it yourself. So you can check your answers: the output is [0, 1, 4, 9, 16, 25].

More From Our Python ExpertsHow to Append Lists in Python

 

3. While Loops

While loops check to see if a condition is true, then repeatedly execute the code as long as the condition is still true. For example:

Iterations = 0

while Iterations < 100:

   Iterations += 1

   print('This is an iteration')

The above code set the number of completed iterations to 0 at the start, indicating the program hadn’t yet processed the while loop. The second line created the while loop, stating the program should execute the following code so long as the variable Iterations equal less than 100. If Iterations remain less than 100, the program runs the following code repeatedly. The code in the loop then proceeds to add one to the value of Iterations, and print a line of code to the console stating the program completed an iteration.

This is a useful tool for responding to data that isn’t entirely predictable. The above example is a bit hollow because it’s coded to run 100 times, which a for loop could also execute well. What if we aren’t looking for a specified number of executions? For instance, what if you want to write code that plays blackjack and always hits when the hand total is less than 16? You could write code that does the following:

  • collects two random cards from the deck and identifies their value

  • opens a while loop with the condition being that hand value is less than 16

  • collect another random card from the deck and identify the new hand value

  • store the final hand value after exiting in the while loop

This code would collect a new card whenever the hand is less than 16 and immediately stop when the hand value is equal to or greater than 16. It would then report the final hand value after making these decisions (and hopefully it’s choices never sent it over 21!).

Learn More About Python5 Ways to Write More Pythonic Code

 

Moving Forward With Control Flow

Control flow is a fundamental aspect of computer programming, critical to creating any scripts that perform logic-based calculations for you, and an important component to becoming fluent in  Python.

I introduced these examples using Python 3 syntax. Don’t forget to always follow your condition statement with a colon, and to indent the line you want executed the same amount — generally good rules to keep in mind when using Python!

What's Next?How to Improve Your Control Flow Coding in Python

This article was originally published on Python in Plain English

Expert Contributors

Built In’s expert contributor network publishes thoughtful, solutions-oriented stories written by innovative tech professionals. It is the tech industry’s definitive destination for sharing compelling, first-person accounts of problem-solving on the road to innovation.

Learn More

Great Companies Need Great People. That's Where We Come In.

Recruit With Us