Get all your news in one place.
100’s of premium titles.
One app.
Start reading
Tom’s Hardware
Tom’s Hardware
Technology
Les Pounder

How to use For Loops in Python

How To Use For Loops in Python

In programming, for loops are incredibly versatile tools to repeat a section of code. For loops can loop for a set number of times using a range, they can have clauses / conditions which will end the loop and we can use them to iterate over items in a dictionary, list or tuple.

In this how to, we will show you how to get started with for loops using Python, the same syntax will also work with MicroPython and CircuitPython on boards such as the Raspberry Pi Pico.

To demonstrate how to use for loops in Python, we will use Thonny, a free, easy to use and cross platform Python editor. 

1. In a browser go to the Thonny website and download the release for your system.

2. Alternatively, install the official Python release using this guide. Note that this guide covers installation on Windows 10 and 11.

Using a Range with Python For Loops

The most basic for loop use in Python is to iterate over a range, essentially creating a loop that will only iterate for a set number of times. While “range” is not strictly part of the syntax for a for loop, it is really a built-in Python function that returns a sequence for a specific pattern, it is the easiest way to demonstrate how a for loop works.

1. Create a for loop and set the range to 10.This will set the value of x to an integer value, starting at 0 and ending at 9. The loop will iterate until it reaches the tenth loop, then it will end.

for i in range(10):

2. Print the current value of i as part of a sentence. Here we use Python’s string format method to insert the loop number each time the loop iterates.

   print("This is loop: {:n}".format(i))

3. Save the code as for_loop_range.py and click Run to start. You should see this output.

This is loop: 0
This is loop: 1
This is loop: 2
This is loop: 3
This is loop: 4
This is loop: 5
This is loop: 6
This is loop: 7
This is loop: 8
This is loop: 9

Complete Code Listing: For Loop With a Range

for i in range(10):
    print("This is loop: {:d}".format(i))

Using a For Loop With RSS Feeds

(Image credit: Tom's Hardware)

To better illustrate how we can use a for loop, let's use a for loop with a range to pull the top five headlines from BBC News’ RSS feed along with their corresponding URL.

1. Install feedparser using pip at a command prompt. Feedparser is an RSS parsing tool that we shall use to read the RSS feed and convert it into a Python dictionary.

pip install feedparser

2. In Thonny, create a new blank Python file and import feedparser.

import feedparser

3. Create an object, newsfeed, and in there store the parsed BBC News feed.

newsfeed = feedparser.parse("http://feeds.bbci.co.uk/news/rss.xml")

4. Use a for loop with a range of five.

for i in range(5):

5. Print the headlines (title) and the URL (link) of the top five stories. Here we are accessing the newsfeed object, which is a dictionary (array) that contains many more dictionaries and lists. Using the keys (entries, title and link) we can get the values that they store. The value of [i] increments, until it reaches 5, then the loop ends. We have how tos covering dictionaries and lists which go into further detail.

   print(newsfeed['entries'][i]['title'])
   print(newsfeed['entries'][i]['link'])

6. Save the code as news_for_loop.py and click Run. You should see the top five news headlines.

Complete Code Listing: Using a For Loop With RSS Feeds  

import feedparser
newsfeed = feedparser.parse("http://feeds.bbci.co.uk/news/rss.xml")
for i in range(5):
    print(newsfeed['entries'][i]['title'])
    print(newsfeed['entries'][i]['link'])

For Loops With an Early Exit

Ranges can also feature an “early exit”. This uses a conditional statement that checks the value of the of the loop (in our case it is stored in i) and if it matches the value, the code breaks and exits.

We’re going to reuse the code from the first example to start us off.

1. Add a conditional test that checks the value of i is the same as 4. In Python == is an operator that checks that one value is the same as another.

   if i == 4:

2. Print a sentence to inform the user that the loop is terminating. This part of the code will only activate once “i” contains the value 4.

       print("This loop sequence terminates at loop {:n}".format(i))

3. Break the loop, forcing the code to stop.

       break

4. Save and run the code. You should see this output.

This is loop: 0
This is loop: 1
This is loop: 2
This is loop: 3
This is loop: 4
This loop sequence terminates at loop 4

Complete Code Listing: For Loop With an Early Exit

for i in range(10):
    print("This is loop: {:n}".format(i))
    if i == 4:
        print("This loop sequence terminates at loop {:n}".format(i))
        break

Nested For Loops

We can have multiple for loops running together. For example we can nest one for loop inside of another. In this example we are reusing the code from the first example.

for i in range(10):
   print("This is loop: {:n}".format(i))

1. Add a nested for loop that will iterate ten times. Ensure that the variable name is different to the main loop, otherwise the two will clash.

   for j in range(10):

2. Add a print statement to inform the user that this is the nested for loop.

       print("This is nested loop: {:n}".format(i))

3. Use a break to exit out of the nested for loop. If we don’t do this, then the nested for loop will repeat each time the main loop iterates.

       break

4. Save and run the code. You should see this output.

This is loop: 0
This is nested loop: 0
This is loop: 1
This is nested loop: 1
This is loop: 2
This is nested loop: 2
This is loop: 3
This is nested loop: 3
This is loop: 4
This is nested loop: 4
This is loop: 5
This is nested loop: 5
This is loop: 6
This is nested loop: 6
This is loop: 7
This is nested loop: 7
This is loop: 8
This is nested loop: 8
This is loop: 9
This is nested loop: 9

Complete Code Listing: Nested For Loops

for i in range(10):
   print("This is loop: {:n}".format(i))
   for j in range(10):
       print("This is nested loop: {:n}".format(i))
       break

Iterating With For Loops

(Image credit: Tom's Hardware)

Iterating over objects in a list, dictionary or tuple is useful if we want to use data from these objects. In this example, we will reuse the code from our RSS feed reader to create a simple web app. A ranged for loop will grab the news headlines from the object, then split the headlines and their URLs apart and then store them inside of a Python dictionary object. Then we will use the dictionary as a source to generate an HTML page in a browser.

1. Install PyWebIO using pip at the command prompt,. PyWebIO is a means to create inputs and outputs around a browser session.

pip install pywebio

2. In Thonny, create a new blank Python file and import feedparser and import three PyWebIO classes. PyWebIO has many different classes and functions, but we are interested in creating a server, outputting information to a browser and controlling the session.

import feedparser
from pywebio import start_server
from pywebio.output import *    
from pywebio.session import *

3. Create an object, newsfeed, and in there store the parsed BBC News feed. This can be any RSS feed that you choose.

newsfeed = feedparser.parse("http://feeds.bbci.co.uk/news/rss.xml")

4. Create an empty dictionary called news_stories. Dictionaries are Python objects that store data using a key, value system. By calling a dictionary and referencing a key, we can get the value attached to it.

news_stories = {}

5. Using a for loop with a range, grab the first five news stories and store them inside the news_stories dictionary. The title (headline) will be the key, and the URL will be the value.

for i in range(5):
   news_stories.update({newsfeed['entries'][i]['title']:newsfeed['entries'][i]['link']})

6. Create a function called main. This function will handle creating the web content to be served.

def main():

7. Set the page title. This is seen in the tab / title bar of the web browser.

   set_env(title='Python For Loops RSS Example')

8. Use a for loop to iterate over every key (k) and value (v) stored in the news_stories dictionary. The for loop will end once it has retrieved all of the keys and values, it does not need a range.

   for k,v in news_stories.items():

9. Place the headline text on the page. PyWebIO’s put_text function places raw text on a web page, and we pass the function the key value, which is the headline.

       put_text(k)

10. Place the URL underneath the headline. Using put_link we generate an HTML hyperlink with the text “Click here”. The URL is created from the value stored in v.

       put_link('Click here',v)

11. Outside of the for loop and the function, start the server. Call the main function and set the port to 8080, and debug to True. It is advisable to set the port to an unused value and typically 8080 is valid. If necessary change this to another value. Setting debug to True is useful as it provides output in the Python shell, and in the browser session.

start_server(main, port=8080, debug=True)

12. Save the code as for_loop_news_dict.py and click Run. The Python shell will display the URL of the generated page.

(Image credit: Tom's Hardware)

13. Click on the URL to open in your default browser. The URL can also be viewed from another device on the network.

(Image credit: Tom's Hardware)

Complete Code Listing: Iterating With For Loops

import feedparser
import time
from pywebio import start_server
from pywebio.output import *    
from pywebio.session import *
newsfeed = feedparser.parse("http://feeds.bbci.co.uk/news/rss.xml")
news_stories = {}
for i in range(5):
   news_stories.update({newsfeed['entries'][i]['title']:newsfeed['entries'][i]['link']})
def main():
   set_env(title='Python For Loops RSS Example')
   for k,v in news_stories.items():
       put_text(k)
       put_link('Click here',v)
start_server(main, port=8080, debug=True)
Sign up to read this article
Read news from 100’s of titles, curated specifically for you.
Already a member? Sign in here
Related Stories
Top stories on inkl right now
One subscription that gives you access to news from hundreds of sites
Already a member? Sign in here
Our Picks
Fourteen days free
Download the app
One app. One membership.
100+ trusted global sources.