How to Improve Your Control Flow Coding in Python

Have you perfected the fundamentals of control flow? These tips and tricks will take your Python game to the next level.
Headshot of author Peter Grant
Peter Grant
Expert Columnist
July 21, 2021
Updated: July 25, 2021
Headshot of author Peter Grant
Peter Grant
Expert Columnist
July 21, 2021
Updated: July 25, 2021

In a recent article I introduced the fundamentals of control flow in Python programming. These critical skills instruct your programs on which sections of code to run, giving you the power to perform the calculations you need to perform for different circumstances.

That said, the techniques I covered were pretty basic and left some efficiency off the table. It was about the fundamentals of control flow after all.

4 Keys to Improving Your Control Flow

  1. Break
  2. Pass
  3. Range
  4. Ternary Expressions

Now I’ll introduce you to some useful tricks that improve the speed, flexibility and readability of your control flow processes: break, pass, range and ternary expressions.

Back to BasicsLearn the Fundamentals of Control Flow in Python

 

1. Break

Break is a useful tool for while loops. Essentially, this function tells the program to break out of the while loop, which  is useful for a few reasons. Most critically, while loops have the problem that they may run forever if the code doesn’t behave as expected. Let’s look at an example:

import random

Total = 0

while Total < 100:

   Total += random.randint(-10,10)

   print(Total)

The above code performs the following steps:

  • It first imports the random package, which generates random numbers.

  • Then the code initializes our variable Total and sets it to zero. This value will track the total of summed random numbers later.

  • Then the code opens a while loop and instructs Python to run that while loop so long as Total is less than 100.

  • Within the while loop, the code creates a new random number between -10 and 10 then adds it to Total. It then prints the new value of total.

This code will continue generating random numbers and adding them to Total until the value of Total reaches or exceeds 100 which should happen eventually. The nature of random numbers means that, with enough attempts, the value should eventually get that high,  but it’s entirely possible that it won’t! What if random.randint(-10, 10) continuously returns a negative number? Or what if the command consistently returns zero? These cases are both incredibly unlikely, but it’s possible, which means it’s possible that this while loop will repeatedly execute forever.

We don’t want that.

This is one handy use for break. Maybe you want to set a limit on how long this code will run to avoid crashing the program and computer. You can set a break condition to exit the loop when you’ve run out of patience. To do this in the above example you could create an iterator, and call break when the iterator reaches a certain threshold. Like this:

import random

Total = 0

i = 0

while Total < 100:

   Total += random.randint(-10,10)

   print(Total)

   i += 1

   if i == 1000000:

      break

This new example added four lines of code. They perform the following actions:

  • The first new line initializes the iterator i and sets it equal to zero, indicating that the while loop has not performed an iteration.

  • The second new line adds one to i every time the while loop executes, keeping track of the number of iterations completed.

  • The third line creates an if statement telling the script to execute a certain section of code only if the while loop has executed 1,000,000 times.

  • The fourth line of code simply says break. This tells the program to exit the while loop, simply giving up on the process.

In this way you can use break to avoid accidentally having while loops crash your code.

More From Our Coding Experts 5 Ways to Write More Pythonic Code

 

2. Pass

Pass is a great trick for working on code that’s currently in development as it enables you to create the structure of the code without knowing what the details of the code are yet. Specifically, it says to skip a certain block of code.

Let’s revisit our previous example with the assumption that you want the code to do something if Total passes a certain negative number. To do that you would add an if statement telling the program what to do when the program passes that threshold. Let’s say the number is -75 and you aren’t yet sure how to code the steps you want the program to take. In that case, your code will appear as follows:

import random

Total = 0

i = 0

while Total < 100:

   Total += random.randint(-10,10)

   print(Total)

   if Total <= -75:

   i += 1

   if i == 1000000:

      break

Can you see what’s wrong with this code? If you’ve read about the fundamentals of control flow I’m sure you see that it’s kind of weird, but you might not yet recognize the real problem. You’ve probably realized that the script won’t run anything special when Total ≤ -75, but you might not yet know that the code won’t run at all.

Python won’t compile and execute scripts that expect an indented block but don’t provide one––and that’s what we have here. After introducing the new if statement, Python expects code to come after it.

Since we don’t yet know what we want to place there, we can use pass as a temporary placeholder. This will provide an indented block, and will instruct Python to simply skip whatever is supposed to occur in that if statement. It also helps if you add a comment reminding yourself to clean it up later.

With those adjustments, our example code appears as follows:

import random

Total = 0

i = 0

while Total < 100:

   Total += random.randint(-10,10)

   print(Total)

   if Total <= -75:

       #Do something when condition is met

       pass

   i += 1

   if i == 1000000:

      break

Boom, done. Now Python knows to skip that section of the code and will execute the script without complaints. This enables you to keep testing the rest of the code until you’re ready to finish working with that if statement.

Before You Go...Perform Financial Data Analysis With Python

 

3. Range

Range is a function that creates an iterator over a specified period. This can be especially useful in for loops. When introducing the fundamentals of control flow I used an example where we already had a list we wanted to iterate over and where we wanted to make use of the data in that list. What if you don’t have that? Instead, what if you know that you need to execute a section of code a certain number of times and don’t need to reference values in a list?

For those cases you can use range to create a list, telling Python how many times it should repeat the for loop. Let’s say you want to perform a loop 10 times. You might do the following:

Iterations = 0

for i in range(10):

   Iterations += 1

   print(Iterations)

This code does four things:

  • First it initializes the variable Iterations, which can be used to track the number of times this code has executed and sets it to zero.

  • Second it uses range to create a list running from zero to nine. This list contains ten entries. Since this list is connected to a for loop it will now run the following code once for each entry in the range, or 10 times. It assigns the value of the list to i, but we don’t really care about that and don’t use it.

  • Within the for loop the code adds one to Iterations indicating the loop has performed one more iteration than it had previously.

  • Finally, it prints the value of Iterations to the console.

If you try running this code you should see that it sequentially prints out the numbers one through 10, which indicates the for loop has executed 10 times.

Learn More From Peter GrantHow to Create Report-Ready Plots in Python

 

4. Ternary Expressions

Ternary expressions don’t actually change how the control flow executes, but they are a handy syntax trick. They allow you to write an if-then-else statement on a single line of code. If the if-then-else statement is not particularly complicated, this can make your code easier to read. (Note that this is only true if the statement isn’t complicated. Complicated statements become a nightmare to read when using ternary expressions).

The basic syntax of a ternary expression is:

ResultValue = ValueIfTrue if condition else ValueIfFalse

To write a ternary expression you need to:

  • Provide the variable name to store the output. In the above code this is ResultValue.

  • Provide the value that should be stored in the output when the if condition is true. In the above code this is ValueIfTrue.

  • Provide an if condition for the code to implement. In the above example this is listed as if condition.

  • Provide the else statement, so the code knows what to do when the if condition is false.

  • Finally, provide an output value when the if condition is false. In the above code this is ValueIfFalse.

To see this as an example, let’s say we want to write a program that can identify hot weather versus cold weather. The program thinking about people in a cold climate, so “hot” is anything above 70 degrees Fahrenheit (21.1 degrees Celsius for those outside of the US). The program will check to see if the temperature is above 70 degrees, return “Hot” if it is, and “Nice” if it isn’t. (The people in our example have no concept of too cold––they're from Minnesota). The code appears as follows:

Comfort = 'Hot' if Temperature > 70 else 'Nice'

Those outside of the US can use the exact same code, but replace 70 with 21.1 to convert the code to metric units, assuming any data you’re connecting the script to is also in metric.

And that’s a ternary expression. An entire if statement written on one line. And since it’s quite a simple if statement, it’s very easy to read and understand.
 

What’s Next?

This article covered some handy tips to improve your control flow code enabling Python scripts that are both more powerful and easier to read. These skills, combined with the basics covered in Learn the Fundamentals of Control Flow in Python, should have you ready to start controlling the flow of logic in your programs!

Readers interested in learning Python may want to know more about how to automate scientific data analysis. If that’s you, consider following my tutorial.

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