Skip to content
Home » Iterating over Ranges in Python

Iterating over Ranges in Python

Spread the love

Today we’ll learn how to iterate over ranges. If you want to learn more about ranges in general, you can read this article.

If you want to repeat some code a fixed number of times, you can use a range. A range is a sequence of numbers, so you can use it to determine how many times the loop should run. Naturally, you also have access to each element of the range (i.e. each number) by means of the variable used for iteration.

So, if you want the loop to run 5 times, you pass 5 to the range function:

 >>> for i in range(5):
 ...     print("This is round number " + str(i + 1))
 ... 
 This is round number 1
 This is round number 2
 This is round number 3
 This is round number 4
 This is round number 5 

You could also rewrite this code using the version of the range function with 2 parameters:

 >>> for i in range(1, 6):
 ...     print("This is round number " + str(i))
 ... 
 This is round number 1
 This is round number 2
 This is round number 3
 This is round number 4
 This is round number 5 

Here the upper bound, which is 6, is not included.

In each loop run, the variable i takes the value of the next element in the range. So, in the first loop run its value is 0, then 1, and so on, up to 4.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply