How to restart a while loop in Python | Example code

  • by

You can use the input() function to restart a while loop in Python. And use the if statement to restart loop count.

Here is the simple syntax for it, use your own logic.

while i < n:
    if something:
       do something
       i += 1
       do something else  
       i = 2 #restart the loop

Example restart a while loop in Python

Simple example code while loop restart if user enter “0”, otherwise loop will run until “i < 5”. To stop it use the break statement.

i = 0
while i < 5:

    restart = (input("Enter 0 to restart loop: "))

    if restart != "0":
        print("Loop ", i)
        i += 1
        print("Loop Restarted")
        i = 0  # restart the loop


How to restart a while loop in Python

Do comment if you have any doubts or suggestions on this Python while loop code.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.