Python - How To Restart a Loop in Python

ID : 447

viewed : 136

Tags : PythonPython Loop

vote vote

95

In Python, we can use for loops and while loops to iterate over linear iterable data structures. We sometimes have to reset the iteration to the beginning during iteration, which is generally not recommended during manipulation. In this article, we will learn how to restart a for loop or a while loop in Python.

Restart a Loop in Python

Generally, loops are used to iterate over some linear data structure or run some piece of code n times. Now, to restart such a loop, we have to reset the iterator or the variable involved in the termination condition so that the loop continues to run. Consider a for loop. In for loops, we usually have an integer i, which iterates n times before its termination. So, to restart a for loop, we will manipulate the value of i. In Python, unfortunately, it is not possible to manipulate the for loop. In other languages, such as Java, C++, C, it is possible.

To get such behavior in Python, we can use a while loop. Refer to the following code. It has two variables, namely, i and n. i is the variable involved in the termination condition. Its value will be reset to 0 when the value of i gets more than or equal to n. The program implements an infinite loop to depict restarting.

i = 0 n = 10  while i < n:     if i < 5:         print(i)         i += 1     else:                  i = 0 # This assignment restarts the loop 

Output:

0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 ... 

  • Related HOW TO?