
When writing in any language, it’s important to not only understand the concept of control flow, but also know how to implement it in the language you’re working in.
Each language is different with how they implement control flow. Here, I’m showing you how it’s implemented in Python.
What is control flow?
Control flow defines how a program makes decisions, repeats logic, or exits execution. There are multiple ways to control your logic in Python:
forandwhileloops - used to repeat a block of codeif,elif, andelsestatements - used to make a decision on whether to execute a block of code.Alternative:
match/case(introduced in Python 3.10)
return- used to exit out of a function/method earlyyield- used to “pause” a function to execute other code; used primarily for generatorsbreakandcontinuestatements - exiting a loop early or moving to the next iteration, respectively.
Loops in Python
Loops are a way to execute the same block of code over and over. In Python, there are 2 kinds of loops that are built-into the language:
# For loop
my_list = [1, 2, 3]
for number in my_list:
print(number)
# While loop
number = 0
while number <= 5:
print(f"Number: {number}")
number += 1A while back I wrote about the difference between a while and a for loop, which can be found here.
» Some languages like Java have do-while loops; Python does not have this natively built-in.
If/Else/Elif statements
These statements help determine what our logic should do based upon certain criteria (“conditions”). For instance, if we’re comparing temperatures:
temperature = 75
if temperature > 85:
print("It's hot.")
elif temperature > 70:
print("It's nice outside.")
else:
print("It's cold.")Based upon the temperature defined at the top, Python will select one of the options.
» As a Floridian, I consider 60 degrees quite chilly. You’ll see me bundled up in a long sleeve and jacket 😤
You’re not limited to using all 3 of these conditions together at the same time like in the example above. For instance, if you want to check against a single condition:
is_error = True
if is_error:
print("Something went wrong.")I’ll have a newsletter in the future taking a deeper dive into these statements coming out later, but I do have a resource that talks about an alternative to if/else statements that was introduced in Python 3.10 here.
return and yield statements in Python
Return statements are ways to retrieve values from a function/method:
import random
def generate_random_number(min = 0, max = 100):
"""Create a random number between a min value (default 0) and a max value (default 100)."""
if min >= max:
raise ValueError("Min has to be less than max!")
return random.randint(min, max)Yield statements, on the other hand, allow us to “pause” the function and do other logic before returning. These are primarily used to create generators, which are discussed in detail in this article.
Python’s break and continue statements
While you’re inside of a loop, you may run into a situation where you may need to exit out of the loop early or continue to the next iteration within the loop.
For instance, if you’re iterating over a list and you found the item you wanted, it doesn’t make sense to continue iterating over it, you’d use break to bail out of the loop:
import random
random_numbers = [
random.randint(0, 100) for _ in range(0, 100)
]
target_number = 5
for num in random_numbers:
if num == target_number:
print("Found it!")
break # get out of the loopOn the contrary, you may want to continue iterating over the loop:
import random
random_numbers = [
random.randint(-100, 100) for _ in range(0, 100)
]
# Search for all positive numbers
for num in random_numbers:
if num < 0:
continue # go to the next number
print(num)I’ve broken the differences between break and continue down further in this article.
Happy coding!
📧 Join the Python Snacks Newsletter! 🐍
Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:
Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.
Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.
Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.
You can unsubscribe at any time.
Interested in starting a newsletter or a blog?
Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.
If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.
This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.


