Skip to content

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 the loop count.

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

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

Example restart a while loop in Python

Simple example code while loop restarts if the user enters “0”, otherwise the 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
    else:
        print("Loop Restarted")
        i = 0  # restart the loop

Output:

How to restart a while loop in Python

The continue statement causes the loop to immediately jump to the next iteration, skipping any code that comes after it within the loop body.

Here’s a more concrete example where the user is prompted to input a number, and if the number is negative, the loop restarts to ask for input again:

while True:
    try:
        num = int(input("Enter a positive number: "))

        if num < 0:
            print("Negative number entered. Please try again.")
            continue

        # Process the positive number here
        print("You entered:", num)

    except ValueError:
        print("Invalid input. Please enter a valid integer.")

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

Note: IDE: PyCharm 2021.3.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 *