1. Home
  2. Training Library
  3. Programming
  4. Programming Courses
  5. Introduction to Flow Control in Python

Introduction to Flow Control in Python

Contents

keyboard_tab
Python Flow Control
Introduction to Flow Control in Python
Overview
Difficulty
Beginner
Duration
10m
Students
23
Description

This course provides an intro to Flow Control, exploring conditionals and types of loops available in Python.

Learning Objectives

  • Describe the concept of flow control
  • List the if-family of conditionals
  • List the types of loops

Intended Audience

This course was designed for first-time developers wanting to learn Python. Existing developers may want to skip.

Prerequisites

This is an introductory course and doesn’t require any prior programming knowledge.

 

Transcript

Hello, and welcome! My name is Ben Lambert, and I’ll be your instructor for this course. 

This course is part of a series of content designed to help you learn to program with the Python programming language. Should you wish to ask me a specific question, you can do that with the contact details on screen. You can also reach support by using the email address: support@cloudacademy.com. And one of our cloud experts will reply.

Have you ever followed bad instructions? Perhaps you’ve attempted to assemble some non-specific Swedish furniture with confusing instructions. Or a poorly written recipe with steps that are out of order or missing. When instructions aren’t clearly defined it can lead to confusion and all kinds of problems. Code is kind of like a recipe. It’s a set of instructions that when followed will produce some desired result. However, code isn’t just a linear list of instructions. It’s more dynamic. Code allows us to decide which instructions to run based on a condition.

For example, we could choose to only call some code if a user is logged in. The code that we write is a set of instructions that the interpreter is going to follow. The interpreter reads through code line by line and follows the instructions. After each instruction is carried out the interpreter moves to the next line until it moves through all of the instructions. As the interpreter progresses through the code it creates a sort of flow. As the interpreter encounters each instruction it determines what to do based on developer-defined conditions. And it branches out in different directions based on these different conditions. The code’s flow determines which instructions will be interpreted at any given time. And for the most part, the conditions that determine the flow are based on data. 

In this lesson, we’ll be reviewing the concept of flow control. Flow control is all about knowing how to make decisions in code. It’s up to us as developers to control the flow of the interpreter by using different language constructs. Let’s explore a simple example of flow control. Let’s play a guessing game. I’m thinking of a number between 1 and 10. 

You need to guess which number and your guess is our input data for this game. Without input, we can’t actually play this game. After all, if there’s no guess we have nothing to compare the number in my head against. Once I have your guess as the input I have to metally compare your guess to the number in my head. If they don’t match, I could ask you to guess again. And we repeat the process until you guess correctly. 

If you guess correctly, I congratulate you on winning and the game is over. While not a complex game, it does a good job at illustrating two unique mechanisms required to control the flow of this game. There’s one mechanism for making decisions and another for repeating actions. Let’s start with decision-making. In this example, after you make a guess, I have to compare your guess against the number in my head, and if they match then you win. 

So, there’s a decision here. Does the guess match? The action that we need to take is different if they match from if they don’t. For making decisions in Python we can use the if keyword with its optional companions elif, and else. The if keyword determines if either a condition is True. If the condition is true the code takes a new path. The if keyword is something you’ll use often as a developer. For example: if some transaction completes successfully then ship the purchaser their product. 

There are two optional keywords that can pair with the if keyword. Sometimes you’ll need to perform a series of decisions based on some conditions. The elif keywords stands for else-if. It can be used after an if statement and allows for multiple related decisions to be checked. Here’s a bit of a contrived example. If this car is blue we charge an extra $4000, else-if it’s red, we charge an extra $5000. We can use zero or more elif statements. We only need to use an elif statement if it makes sense for the decision being made.

We can also use the optional else keyword. Else is intended to be the final - and default decision. The first decision is up to the opening if statement. Then we can have some optional else-if statements. And if none of those are True, then we can make a default decision. As an example: Imagine I ask you your favorite programming language. My response to you might be different depending on which language you pick. If you respond “python”, perhaps I respond one way. Else-if you respond “java”, then I say something else. Else-if you respond “assembly”, I respond a third way. And for all other languages maybe I respond with some default. 

These three keywords are used for flow control by enabling us to make decisions. If we go back to our guessing game example from earlier we can look into repeating actions. Recall that until you guess correctly I’m going to repeatedly ask you to guess a number. Being able to repeat an action is important for controlling the flow of code. These repeated actions are referred to as loops. There are different reasons that you might want to repeat an action. And because there are different reasons for repeating actions, Python provides different types of loops. These loops are called for loops and while loops. 

Our guessing game is an example of a while loop. While loops are used to repeat an action an unknown amount of times. In our example, we repeat until you guess it correctly. A while loop repeats until some condition is False or until we explicitly break the loop. For example: while the game is running: render the graphics. The condition here depends on if this bound name is True. This loop will remain running as long as this bound name is True. If this name is set to False, this loop will stop. There’s another way to stop a loop. You can use the break keyword to stop a loop. 

For example: while True: ask for a guess. If it equals nine then they won and we need to break out of the loop. When the interpreter encounters the break keyword it breaks out of the current loop. You’ll want to be mindful when using while loops. If a loop doesn’t stop then it becomes an infinite loop. Which means the loop will continue forever until the application is stopped. As data flows through your code conditional statements such as if can change the direction of the flow and make it branch out. When our flow reaches a loop the flow pattern changes and you remain in that loop until it stops. 

So, while loops are used to repeat a task based on some condition remaining True. And they stop when the condition becomes False, or they're broken for example using the break keyword. There’s another type of loop referred to as a for loop. For loops are used to loop over a constrained collection of objects. What exactly does that mean? A constrained collection of objects? That implies that there is a collection of objects. And that collection will be constrained to some maximum number of objects. For loops are often used to loop through all of the objects in a list and perform some operation. 

For example:  for each email address in this list, send our welcome email. The for loop is interesting because as it loops over the collection it takes the next object and binds it to a name of our choosing. In this example we’re binding the name email_address to the next object in the list. Then inside the loop itself, we can use that object. This will make more sense once we go into lists more in-depth. So, for loops are different from while loops because they have some sense of constraints. We loop over each object in the collection and perform some operation using the name-bound object. 

Because the collection shouldn’t be infinite we have some sense of constraint and don’t always need to consider breaking out of the loop. Even still you can break out of a for loop. Imagine if you were searching a list for something. As soon as you find it, you don’t need to keep looping. For example: loop over each player in the collection of players and check if they’re player one. If so, tell them how to start the game. Then break the loop. Since the flow of the application gets trapped inside loops until they complete, you’ll want to try and break out of a loop when it’s practical. 

Python reads code from the top of a file to the bottom. And the flow of that code kind of resembles a river. We can divert the code river using conditional statements to make decisions. And we can suspend that flow in a loop and break out when needed. And with that, we should break here. We’ll cover the syntax for conditionals and loops in future content. For now, here are your key takeaways:

  • Flow control determines how data flows through our code.
  • Decisions can be made using if statements along with if’s optional friends elif and else.
  • Loops enable code to repeat actions and different looping needs require different types of loops.
  • While loops repeat until a condition is met or the loop is broken.
  • For loops repeat for each object in a collection and can be brown if needed.

 Thanks so much for watching. And I’ll see you in another lesson!

About the Author
Avatar
Ben Lambert
Software Engineer
Students
81688
Labs
4
Courses
26
Learning Paths
31

Ben Lambert is a software engineer and was previously the lead author for DevOps and Microsoft Azure training content at Cloud Academy. His courses and learning paths covered Cloud Ecosystem technologies such as DC/OS, configuration management tools, and containers. As a software engineer, Ben’s experience includes building highly available web and mobile apps. When he’s not building software, he’s hiking, camping, or creating video games.

Covered Topics