Search code examples
pythonrestartkeyboardinterrupt

Interrupting and restarting a python script


Let's say that I have a script that looks like this

myInput = input(int('Enter a number: '))
while myInput > 0:
    print(myInput)
    myInput-=1

Is there a way that I can interrupt the while loop and return to the part that asks for user input?


Solution

  • Assuming you are referring to a KeyboardInterrupt:

    def foo():
        try:
            myInput = int(input('Enter a number: '))
            while myInput > 0:
                print(myInput)
                myInput-=1
            return True
        except KeyboardInterrupt:
            return False
    
    while not foo():
        pass