Skip to content
Advertisement

What code can I put in to clear all previous user inputs and re-run the code from the top?

I am currently writing a code that accepts user inputs. However, I intend to put in an option such that if the user made an error, they may restart the process again by typing in a specific input. And I’m hoping that the code clears all previous input from the namespace:

For example

name = input("what is your name: ")
age = input("how old are you:? ")
## if the user realizes that they put in the wrong name and wish to restart the process, they may input "restart"
if age == 'restart':
    ### I don't know what code to put here.
else:
    #I'd continue the rest of my codes

I’d greatly appreciate any tips.

Advertisement

Answer

Supposedly you want the console to clear if the user decides to change its input in name

import os     

while True:
    os.system('clear')   #we imported "os" for this built-in function
    name = input("Enter your name: ")
    age = input("how old are you:? ")

    if age == 'restart': #if user inputs 'restart' we head back to the start of the loop
        input("Press Enter Key to Continue...")
        continue

# Rest of the code goes here
    
Advertisement