Blog
Pricing
Python Loops Explained:
Here is How to Master
Them
Categories Python Guides
Written by:
Nathan Rosidi
Author Bio
April 26th, 2024
Main Topics
Types of Python Loops
for loop
while loop
for loop syntax
How to iterate over sequences (lists, tuples,
dictionaries, sets, strings)
Use of the range() function
Nested for loops
Practical examples of Python for loop
while loop syntax
Condition-based nature of while loops
Creating in@nite loops with a while
Nested while loops
Practical examples of Python while loop
Loop Control Statements
break, continue, and pass
Examples of these statements
Advanced Topics of Python Loops
Generators
List Comprehensions with Conditional
Logic
Best Practices and Common Mistakes
Best Practices
Common Mistakes
Conclusion
Share
Follow
Discover the power and 1exibility of Python loops to
automate repetitive tasks and streamline your coding
projects e=ciently.
How can computers do the same things inde@nitely, at
precisely the same time, and with no mistakes?
Loops are the @rst element introduced when we start
Python lessons. They are a simple concept but a
potent tool for enabling computers to think and act
independently.
In this article, I will demonstrate how to use for- and
while-loops in Python and why you should use them to
make your code robust.
What are Python
Loops?
Loops in Python allow you to run a code block more
than once. It is useful when you must do repetitive
tasks and don’t want to write this code multiple times.
For example, Python loops can automate the process
of analyzing large datasets.
Types of Python Loops
Python has two main loops: for and while. Their
programming uses are unique from each other.
For loop: It works best when looping types of
sequences like lists, tuples, dictionaries, Python
sets, and strings.
While loop: It acts as long as the condition
remains true.
Let’s see them in action.
for loop
The for loop in this example loops through the list of
fruits, and the receiving value of the item assigned to
the fruit variable is iterated in each bracket. Let’s see
the code.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Here is the output.
while loop
Here, the while loop continues to the extent that count
< 5 exists. It then executes those parts of the code in
the loop by printing the value of count, which is then
incremented by one.
The execution of the code stops at the count of 5 once
that condition becomes false. Here is the comment.
count = 0
while count < 5:
print(count)
count += 1
Here is the output.
The for Loop
First, let’s see the syntax of it.
for loop syntax
Python for loop syntax is simple:
for variable in sequence:
# Perform actions using variable
How to iterate over sequences
(lists, tuples, dictionaries, sets,
strings)
One can iterate over any sequence type with a for loop
in Python. For example, the most common sequence
type in data science is a list of data points.
Example: imagine that we have a list of temperatures
in Celsius and want to convert them into Fahrenheit.
We can do that with the following code.
In the following code, we begin with the list of
temperatures, loop through each temperature,
transform it into Fahrenheit, and add it to the new list
of temperatures_fahrenheit. Let’s see the code.
temperatures_celsius = [22, 25, 17, 15, 18]
temperatures_fahrenheit = []
for temp in temperatures_celsius:
temperatures_fahrenheit.append((temp * 9/5) +
print(temperatures_fahrenheit)
Here is the output:
Use of the range() function
The range() function is helpful when producing a series
of numbers.
Example: To illustrate, considering the data context,
we may want numbers from 1 to 7 to prepare a list of
them to represent days in a week for a statistical
study.
Therefore, range(7) in the subsequent example yields
numbers between 0 and 6, which aligns with the days
of the week we studied.
for day in range(7): # Generates numbers 0 to 6
print(f"Study day: {day}")
Here is the output.
Nested for loops
A nested for loop is a loop in which the for loop can be
employed to loop within a loop. This concept is
generally used when dealing with multi-dimensional
data.
Example: Let’s say you will analyze data by collecting
data from multiple sensors across different days.
The following is some example code:
sensors = ["Temperature", "Humidity"]
days = ["Monday", "Tuesday", "Wednesday"]
for sensor in sensors:
for day in days:
print(f"Analyzing {sensor} data for {day}"
Here is the output.
Practical examples of Python for
loop
We can take our example of temperature conversion
and classify them as either “Cold,” “Warm,” or “Hot”
according to their Fahrenheit value.
The code block below takes each temperature from
the list in Fahrenheit, classi@es it, and prints the
appropriate message.
for temp in temperatures_fahrenheit:
if temp < 59:
print(f"{temp}F is Cold")
elif temp <= 77:
print(f"{temp}F is Warm")
else:
print(f"{temp}F is Hot")
Here is the output.
The while Loop
The while loop repeats as long as a condition is True.
while loop syntax
Here is the syntax;
while condition:
# code to execute
Condition-based nature of while
loops
When unsure how often a block of code should
execute, consider using a while loop.
In some cases in data science, a while loop may need
to run until you reach a threshold, such as the accuracy
of a model.
Creating inInite loops with a while
An in@nite loop runs forever unless explicitly broken. It
is usually not recommended but valuable when one
wants to keep a server running to handle requests or
other speci@c reasons.
Example: Considering our previous example of
temperatures, let’s imagine a data stream of
temperatures where we continuously keep reading
temperatures until a command ‘Stop’ is encountered.
Let’s see the code.
temperature_stream = iter(["22", "25", "Stop", "17
temperature = next(temperature_stream)
while temperature != "Stop":
print(f"Received temperature: {temperature}")
temperature = next(temperature_stream)
Here is the output.
Nested while loops
You can use a nested while loop if you have more than
one condition inside each other. It might look
complicated. However, the application of it is
straightforward, which you can understand from the
following example.
Let’s see the code.
data_stream = iter(["Batch1-Data1", "Batch1-Data2"
try:
batch = next(data_stream)
while batch != "Stop":
print(f"Processing {batch}")
data_point = next(data_stream)
while data_point != "End":
print(f" Data point: {data_point}")
data_point = next(data_stream)
batch = next(data_stream)
except StopIteration:
print("Finished processing all batches.")
Here is the output.
This approach emulates data processing in batches,
each having multiple data points, terminating upon the
arrival of the “Stop” batch. Here, the “End” signi@ed the
conduction of each such batch.
Practical examples of Python while
loop
Having illustrated how temperature processing was
done before, we can now introduce a condition to stop
the loop if the temperature is above some threshold,
which means a sensor error. Below is our code:
# Simulating a stream with a high temperature
temperature_stream = iter(["22", "25", "33", "Stop
temperature = next(temperature_stream)
while temperature != "Stop":
if temperature == "33": # Assuming 33 indicat
print("Sensor error detected, stopping.")
break
print(f"Received temperature: {temperature}")
temperature = next(temperature_stream)
Here is the output.
Loop Control Statements
Loop control statements change the execution of a
loop from its typical sequence. They are crucial for
managing the 1ow of loops e=ciently, especially in
complex logic scenarios.
break, continue, and pass
break: Stop the loop without iterating.
continue: Continue with the next iteration after
skipping the current loop code.
pass: Do nothing; it's a placeholder for future
code.
Examples of these statements
Now we learn “break,” “continue” and “pass”
statements. But, to solidify our understanding, let’s use
them in one example to see how they can handle
different situations.
In this example, we will see a simulated data stream
where we will ignore temperature below 20, and if
there is a sensor error, we’ll break the loop with an
error. Otherwise, we’ll continue. Let’s see the code.
# Simulated data stream
temperature_stream = iter(["19", "22", "25", "Sens
for temperature in temperature_stream:
if temperature == "Sensor Error":
print("Sensor error detected, stopping.")
break # Exiting the loop on error
elif int(temperature) < 20:
continue # Skipping this iteration
# Placeholder for future logic
print(f"Logged temperature: {temperature}")
Here is the output.
Advanced Topics of Python
Loops
There are many advanced things you can learn about
loops in Python. These can help you handle challenges
better. In the following sections, generators and list
comprehensions are discussed. Let’s start with
Generators.