TNS
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
NEW! Try Stackie AI
Python

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
Featued image for: How to Use Loops in Python
Feature image by Prawny from Pixabay.

Eventually, on your journey with Python, you’re going to run into a need to create a loop.

What is a loop? Other than a fruity breakfast cereal, a loop is a portion of code that repeats a set number of times until a desired process is complete.

Here’s an example of a loop that many can relate to. You go to the ATM, insert your card, and start with your transaction. First, you check your balance, then you remove money from your account. The loop keeps running with each transaction until you tell the ATM you are finished.

Another example would be a program that keeps track of student’s grades. You might use the program to view the grades of every student in the class. The loop will continue from the first student and doesn’t exit until it displays the grades of the final student.

Loops are very useful for all types of applications.

There are three different types of loops that are supported in Python:

  • 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.

Let’s see how both the for and while loops can be used in Python.

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:


We define the variable colors with our set, like so:


Let’s create a for loop for that set. Create the file with the command:


In that file, paste the following:


Save and close the file. Run the script with the command:


You probably already know what the output will be, which is:


The for loop iterated through our entire set and printed out each element from the set.

You can also use for loops with a break statement. What this does is stop the loop as soon as it reaches whatever we’ve set as the break. For example, say you want to stop the loop as soon as it reaches green. For that, we use the if x statement and the break command like so:


Save and close the file. Run the command and the output will end when it reaches green.

We can also use a for loop with different types of elements (lists, tuples, strings, and dictionaries). We’ll use the same entries (red, blue, green, yellow) for each element.


We use the \n in our print definitions as a carriage return, so our output is broken into sets. When we run the script, the output will be:

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:


Next, we define our while loop such that it iterates so long as count is less than 5 with the line:


We now define our iteration, such that each step is increased by 1 with:


Finally, we define what to print out until the count reaches its limit with the line:


The entire Python script looks like this:


Save and close the file. Run the script with:


The output will be:


You’re probably thinking, “But the loop was supposed to stop iterating before the count reaches 5. Remember we started the count at 0, so it will iterate 0, 1, 2, 3, 4 times which outputs five lines of our defined text.

We can also use the else statement in a while loop. Sticking with our example above, we’ll iterate through the loop, and once it reaches our count < 5 statement, it will print something different. The script looks like this:


When you run this script, the output will be:


You can have a bit of fun with an infinite while loop that will keep printing Hello New Stack! over and over. That script looks like this:


If you run the above script, it will keep printing Hello New Stack! until you kill it with the Ctrl+C keyboard combination.

And that’s your basic introduction to Python loops. Loops are a very handy feature to use and will serve you in numerous use cases for your Python programming.

Created with Sketch.
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.