How to restart code in Python
Learn how to restart Python code with our guide. Discover different methods, tips, real-world applications, and how to debug common errors.

Developers often need to restart a Python script. This action lets you reset program state or recover from errors without a full stop, which improves application resilience.
In this article, we'll cover several techniques to restart your code. You'll find practical tips, real-world applications, and debugging advice to help you choose the best method for your project.
Using a simple while loop for restarting code
def main():
print("Hello World!")
# Main code logic goes here
restart = True
while restart:
main()
user_input = input("Restart the program? (y/n): ")
restart = user_input.lower() == 'y'--OUTPUT--Hello World!
Restart the program? (y/n): y
Hello World!
Restart the program? (y/n): n
This method wraps your main program logic inside a main() function. A while loop then repeatedly calls this function as long as the restart variable is true. This structure neatly separates the core application from the restart mechanism, making the code cleaner and easier to manage.
After each execution, the script prompts for user input. Your response determines the loop's fate—entering 'y' keeps the restart variable true, triggering another cycle. Any other input sets it to false, gracefully ending the program.
Basic restart methods
The while loop is a solid starting point, but other fundamental techniques can also give you precise control over restarting your Python script.
Using a break statement with an infinite loop
while True:
print("Running the program...")
# Main code logic goes here
if input("Restart? (y/n): ").lower() != 'y':
break
print("Program ended")--OUTPUT--Running the program...
Restart? (y/n): y
Running the program...
Restart? (y/n): n
Program ended
An infinite loop using while True offers a more direct way to handle restarts. Instead of managing a boolean flag, you simply run the code indefinitely until a specific condition is met to exit.
- Your main logic executes on each iteration of the loop.
- The script then waits for your input. If you enter anything other than
'y', the condition in theifstatement is met. - This triggers the
breakcommand, which immediately stops the loop and allows the program to finish.
Using recursion to restart program flow
def run_program():
print("Program is running...")
# Main code logic goes here
if input("Restart? (y/n): ").lower() == 'y':
run_program() # Recursive call to restart
else:
print("Program terminated")
run_program()--OUTPUT--Program is running...
Restart? (y/n): y
Program is running...
Restart? (y/n): n
Program terminated
Recursion offers another route for restarting your program. The run_program() function simply calls itself when you want to restart, creating a new execution of the main logic.
- If you enter
'y', the function makes a recursive call to itself. - Any other input allows the current function to finish. This lets the previous one finish, unwinding the calls until the program stops.
While elegant, this method has a major drawback. Each restart adds to the call stack, and too many can cause a stack overflow error, crashing your script due to excessive memory on the call stack.
Using a flag variable with conditional logic
running = True
while running:
print("Executing main program...")
# Main code logic goes here
user_choice = input("Options: [r]estart, [q]uit: ")
if user_choice.lower() == 'q':
running = False
print("Program finished")--OUTPUT--Executing main program...
Options: [r]estart, [q]uit: r
Executing main program...
Options: [r]estart, [q]uit: q
Program finished
This method gives you more explicit control by using a boolean flag—in this case, running—to manage the program's state. The while loop continues executing as long as this flag remains True.
- After each cycle, the script asks for your input.
- Choosing to quit by entering
'q'sets therunningflag toFalse, which stops the loop. - Any other input allows the loop to continue, effectively restarting the main logic.
Advanced restart techniques
While the basic methods are effective, more advanced techniques offer robust solutions for handling complex restart scenarios in larger applications.
Using a restartable decorator for functions
def restartable(func):
def wrapper(*args, **kwargs):
while True:
result = func(*args, **kwargs)
if input("Restart? (y/n): ").lower() != 'y':
return result
return wrapper
@restartable
def my_program():
print("Program running...")
return "Completed"
my_program()--OUTPUT--Program running...
Restart? (y/n): y
Program running...
Restart? (y/n): n
A decorator offers a clean way to add restart logic to any function. The restartable decorator wraps your function—in this case, my_program—inside an infinite while True loop. This approach keeps your code reusable by separating the restart mechanism from the core program logic.
- The
@restartablesyntax applies the decorator to themy_programfunction. - On each loop, your function runs, and then the script asks if you want to restart.
- If you enter anything other than
'y', the loop exits, and the program ends.
Using the subprocess module to restart the script
import sys
import subprocess
def restart_program():
python = sys.executable
subprocess.call([python] + sys.argv)
print("This program will restart itself")
if input("Restart now? (y/n): ").lower() == 'y':
restart_program()--OUTPUT--This program will restart itself
Restart now? (y/n): y
This program will restart itself
Restart now? (y/n): n
Using the subprocess module offers a more powerful restart by launching a completely new process of your script. This method provides a true "hard reset" because it doesn't share memory or state with the original process, making it ideal for applications that need to clear everything and start fresh.
- The
restart_program()function usessys.executableto find the path to the current Python interpreter. - It then calls
subprocess.call(), passing in the interpreter path along withsys.argv, which contains your script's name and any command-line arguments.
This approach effectively tells the operating system to run your script again from the very beginning.
Using sys.exit() with command line arguments
import sys
import subprocess
if len(sys.argv) > 1 and sys.argv[1] == "restarted":
print("This is a restarted instance")
else:
print("First run of the program")
if input("Restart? (y/n): ").lower() == 'y':
python = sys.executable
sys.exit(subprocess.call([python, sys.argv[0], "restarted"]))--OUTPUT--First run of the program
Restart? (y/n): y
This is a restarted instance
Restart? (y/n): n
This method combines subprocess with command-line arguments to create a more intelligent restart. It allows your script to know whether it's being run for the first time or has been restarted, which lets you execute different logic for each case.
- The script checks
sys.argvfor a"restarted"flag to determine its state. - When you choose to restart,
subprocess.call()launches a new instance of the script, passing this flag. sys.exit()then terminates the original process, preventing multiple instances from running simultaneously. This gives you a clean handoff between the old and new script executions.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. You can move beyond learning individual techniques and build complete apps with Agent 4, which handles everything from writing code to connecting databases and deploying your project.
Instead of piecing together restart logic, describe the interactive tool you want to build:
- An interactive calculator that solves an equation and then prompts the user to enter another one.
- A batch file converter that processes a file and then asks to run again with a new one.
- A dashboard that fetches and displays real-time data, with an option to refresh the feed on command.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
While restarting scripts is useful, you'll need to watch out for a few common pitfalls that can trip up your code. When these issues arise, code repair techniques can help you identify and fix the problems automatically.
Avoiding stack overflow with recursive restart() functions
Using recursion to restart a function seems clever, but it's risky. Each time a function calls itself, it adds a new frame to the call stack. If your script restarts too many times, you'll hit Python's recursion depth limit and trigger a stack overflow error, which crashes the program.
- This issue is specific to recursive solutions like calling
run_program()from within itself. - Iterative methods, such as using a
whileloop, are safer because they don't add to the call stack with each cycle. They simply repeat the code block.
Resetting variables between program restarts
A common mistake is failing to reset variables, leading to unexpected behavior. If a variable is defined outside your main restart loop, its value will persist across restarts. This can corrupt the state of your program on subsequent runs.
- To fix this, make sure you initialize or reset all necessary variables inside the loop or function that gets re-executed.
- This ensures that every restart begins with a clean slate, just as if the program were run for the first time.
Preventing infinite loops in restart logic
Your restart mechanism can accidentally create an infinite loop if the exit condition is flawed. For example, if your code expects the user to type 'quit' but you only check for 'q', the loop will never receive the signal to break and will run forever.
- Always double-check the logic that controls your loop's exit. Ensure the condition can be met.
- Carefully test all possible user inputs to confirm that the program terminates correctly when it's supposed to.
Avoiding stack overflow with recursive restart() functions
While recursion offers a seemingly straightforward restart path, it's a risky approach due to how Python manages function calls. Each recursive step adds a new frame to the call stack, and this stack has a finite size, leading to a crash.
The following example with the run_with_restart() function illustrates how quickly this limit can be reached, causing a stack overflow.
def run_with_restart():
print("Running main program...")
choice = input("Restart? (y/n): ")
if choice.lower() == 'y':
run_with_restart() # Recursive call that can lead to stack overflow
print("This line only executes when not restarting")
run_with_restart()
Each time you restart, the run_with_restart() function calls itself without finishing the previous call. This piles up unfinished functions on the call stack, leading to an inevitable crash. See how to fix this with the corrected code below.
def run_program():
while True:
print("Running main program...")
choice = input("Restart? (y/n): ")
if choice.lower() != 'y':
break
print("Program ended")
run_program()
The corrected code swaps recursion for a more stable iterative approach. This change is crucial for preventing stack overflow errors, especially in scripts that might restart frequently.
- It uses a
while Trueloop to run the program's logic indefinitely. - When you enter anything other than 'y', the
breakstatement executes, safely terminating the loop and ending the program without consuming extra memory on the call stack.
Resetting variables between program restarts
Failing to reset variables between restarts can lead to unexpected behavior. When a variable is defined outside the main loop, its value persists across runs. This corrupts your program's state, causing bugs that are often tricky to diagnose and fix.
The following code demonstrates this problem. Notice how the counter variable retains its value with each restart instead of resetting as you might expect.
counter = 0 # Global counter
def main():
global counter
counter += 1
print(f"Run #{counter}")
# Main logic here
restart = True
while restart:
main() # Counter keeps increasing across restarts
restart = input("Restart? (y/n): ").lower() == 'y'
Because the counter is defined outside the while loop, it never resets. Each restart simply increments the existing value instead of starting fresh. The following example shows how to correct this behavior.
def main():
counter = 1 # Local counter reset each time main() is called
print(f"Run #{counter}")
# Main logic here
restart = True
while restart:
main()
restart = input("Restart? (y/n): ").lower() == 'y'
The fix is simple: move the counter initialization inside the main() function. This makes counter a local variable, so it’s reset to its starting value every time the while loop calls main(). This change ensures each restart begins with a clean slate, preventing data from one run from affecting the next. Keep an eye on variable scope whenever you're building restart logic that relies on loops.
Preventing infinite loops in restart logic
An infinite loop can trap your script if the exit condition is flawed. This often happens when your code doesn't account for all possible user inputs, like checking for 'y' but not 'Y', causing the program to repeat endlessly.
The following code demonstrates how a simple oversight can cause this problem. Notice how the loop's logic fails to handle different cases for the same user intention, leading to an unintentional infinite loop.
restart = 'y'
while restart == 'y':
print("Program running...")
restart = input("Restart? (y/n): ")
# Missing .lower() can cause infinite loop if user enters 'Y'
The strict comparison restart == 'y' doesn't account for an uppercase 'Y', causing the program to terminate when it should restart. The following code shows how to fix this with a more robust check.
restart = 'y'
while restart == 'y':
print("Program running...")
restart = input("Restart? (y/n): ").lower()
The corrected code makes the loop more robust by converting user input to a consistent format. This simple change prevents the program from ending when you don't want it to.
- The
.lower()method is added to theinput()function, so an entry like 'Y' is automatically changed to 'y'. - This ensures the
while restart == 'y'condition works as expected, preventing an accidental exit from the loop.
Real-world applications
Beyond avoiding common errors, these restart techniques are fundamental for building resilient and interactive real-world applications.
Implementing a retry mechanism for file operations
File operations are notoriously fragile. A script might fail if a file is temporarily locked, a network path is unavailable, or a user simply mistypes a filename. Instead of letting your program crash, you can use a restart loop to implement a retry mechanism.
This approach makes your application far more robust. You can wrap the code that opens or processes a file inside a try...except block within a while loop. If an error like FileNotFoundError occurs, the except block can catch it, inform the user, and prompt them to enter the correct path, allowing the loop to try again.
Creating a simple number guessing game with the random module
Games are a classic example of where restart logic shines, creating an engaging and continuous experience. A number guessing game, for instance, is built around a core loop of guessing and receiving feedback until the correct number is found. With vibe coding, you can rapidly prototype such interactive games by describing the behavior you want.
Once a round is over, you don't want the program to just end. By placing the entire game logic inside a function and calling it from a while loop, you can easily ask the player if they want to play again. This outer loop handles the restart, calling the game function to generate a new secret number with the random module and begin a fresh round.
Implementing a retry mechanism for file operations
This example combines a while loop with a try...except block, giving your script several attempts to open a file and gracefully handling a FileNotFoundError.
filename = "data.txt"
max_attempts = 3
attempt = 0
while attempt < max_attempts:
try:
with open(filename, 'r') as file:
print(f"Successfully opened {filename}")
break
except FileNotFoundError:
attempt += 1
print(f"Attempt {attempt}: File not found")
This code creates a robust file-opening mechanism. It uses a while loop to try opening data.txt up to three times, controlled by the max_attempts variable.
- The
tryblock contains the core logic, attempting to open the file. - If the file opens successfully, a message is printed, and the
breakstatement exits the loop. - If a
FileNotFoundErroroccurs, theexceptblock catches the error, increments theattemptcounter, and allows the loop to try again.
This structure prevents the script from crashing if the file isn’t immediately available.
Creating a simple number guessing game with the random module
This number guessing game demonstrates how a simple restart loop can create an engaging experience by letting players start a new round immediately.
import random
def play_number_game():
target = random.randint(1, 10)
guess = int(input("Guess a number between 1 and 10: "))
if guess == target:
print(f"You won! The number was {target}")
else:
print(f"You lost. The number was {target}")
while True:
play_number_game()
if input("Play again? (y/n): ").lower() != 'y':
print("Thanks for playing!")
break
This code neatly separates the game's core logic from its restart mechanism. The entire gameplay for one round is self-contained within the play_number_game() function, which handles number generation and checks your guess.
- An outer
while Trueloop repeatedly calls this function to start a new game. - After each round, the script asks if you want to play again.
- If your input isn't
'y', thebreakstatement executes, terminating the infinite loop and ending the program.
This structure makes the code easy to read and manage.
Get started with Replit
Turn these restart techniques into a real tool. Tell Replit Agent: "Build a currency converter that asks to run again" or "Create a tool that processes a file and prompts for another."
Replit Agent will write the code, test for errors, and deploy your application. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



