How to Use Loops in Python
A loop is a portion of code that repeats a set number of times until a desired process is complete. Here's how to do loops in Python.
Feb 22nd, 2024 4:00pm by
Feature image by Prawny from Pixabay.
- For loop – is used for sequential traversing of lists, settings, or arrays. For loops can be used to iterate over a range.
- While loop – is used to execute a block of statements until a given condition is met.
- Nested loops – one loop inside another.
What You’ll Need
The only thing you’ll need is an operating system with Python3 installed. I’ll demonstrate this on Ubuntu Budgie with Python version 3.11.6. You can do this on MacOS or Windows as well. Just make sure you have an updated version of Python installed.The For Loop
The first loop we’ll examine is the for loop, which is the easiest to use. Remember, the for loop is used to iterate through a sequence (such as a list, a tuple, a dictionary, a set, or a string). Let’s say you have a set of colors, which are red, blue, green, and yellow. The set will look something like this:
["red", "blue", "green", "yellow"]
colors = ["red", "blue", "green", "yellow"]
nano for.py
colors = ["red", "blue", "green", "yellow"]
for x in colors:
print(x)
python3 for.py
red
blue
green
yellow
colors = ["red", "blue", "green", "yellow"]
for x in colors:
print(x)
if x == "green":
break
print("Lists")
l = ["red", "blue", "green", "yellow"]
for i in l:
print(i)
print("\nTuple")
t = ("red", "blue", "green", "yellow")
for i in t:
print(i)
print("\nString")
s = "Colors"
for i in s:
print(i)
print("\nDictionary Iteration")
d = dict()
d['colors'] = 123
d['colors'] = 345
for i in d:
print("%s %d" % (i, d[i]))
print("\nSet")
set1 = {"red", "blue", "green", "yellow"}
for i in set1:
print(i),
Lists
red
blue
green
yellow
Tuple
red
blue
green
yellow
String
C
o
l
o
r
s
Dictionary Iteration
colors 345
Set
green
red
blue
yellow
The While Loop
Let’s create a simple while loop that prints out a string of text until the count remains below five, at which point the loop ends. For this type of loop, we’ll make use of count (which keeps track of our iterations), while (is the actual while loop), and print (which prints the string of text to the output). First, we define that the count starts at 0 with the line:
count = 0
while (count < 5):
count = count + 1
print("Hello New Stack!")
count = 0
while (count < 5):
count = count + 1
print("Hello New Stack!")
python3 while.py
Hello New Stack!
Hello New Stack!
Hello New Stack!
Hello New Stack!
Hello New Stack!
count = 0
while (count < 5):
count = count + 1
print("Hello New Stack!")
else:
print("Goodbye New Stack!")
Hello New Stack!
Hello New Stack!
Hello New Stack!
Hello New Stack!
Hello New Stack!
Goodbye New Stack!
count = 0
while (count == 0):
print("Hello New Stack!")
YOUTUBE.COM/THENEWSTACK
Tech moves fast, don't miss an episode. Subscribe to our YouTube
channel to stream all our podcasts, interviews, demos, and more.