How to Create an Infinite For Loop in Python



Python


In this article, we show how to create an infinite for loop in Python.

We will show how to create an infinite loop for a range of values, a single value, and for a string.



How to Create an Infinite Loop for a Range of Values

Using the the range() function in Python, we can set up a range that goes from one value to a certain value, such as 1 to 3, and then have this repeat infinitely using the cycle() function from the itertool module.

This way, we can create an infinite loop between a certain range in Python.

So below we have a program that cycles between the values 1-9 infinitely.



So the first thing we must do is import is import the itertools module.

We then create a range that we want to loop through. In this case, we want to loop repeatedly through the numbers 1-3. So we use the range() function and pass in 1-4 as the parameter. Remember that the first parameter of a range() function is inclusive while the second parameter is excluded. Therefore, it doesn't display the number 4 but goes up to the number 3.

We then use a for loop with the cycle() function to loop repeatedly through this range.

When you run this program, the numbers 1,2,3 show repeatedly without end in an infinite loop.

You would have to interrupt the program by pressing Ctrl+C to break the infinite loop.

How to Create an Infinite Loop for a Single Value

What if you didn't want to repeat a range of values but instead wanted to wanted to repeat a single value infinitely?

For example, let's say you want to repeat the number 100 infinitely.

There are 2 ways of doing this.

One way is to again use the range function.

This is shown in the code below.



Another way and perhaps better way of doing it is to create a list composed of that element as the only constituent of that list.

Below is another way of repeating the number 100 infinitely in Python.



In this manner, we create a list composed of a single integer, 100.

We then cycle through this list of only one element, which repeats 100 infinitely.



How to Create an Infinite Loop for a String

In the same manner as above, we can create an infinite loop for a string.

We do this by creating a list composed of the string we want to repeat.

This is shown in the code below.



Make sure that to repeat a string with the cycle() function, put the string within a list by itself.

If you set the variable equal to a string not in a list, the cycle() function separates each character from the string, which is probably not what you want. So to repeat an entire string, it must be within a list with that string being the only element of a list.

And this is how you can create an infinite for loop in Python using the cycle() function of the itertools module.


Related Resources

How to Extract All Files and Folders from a Zip File in Python

How to Read the Contents of a Zip File in Python



HTML Comment Box is loading comments...