python – How do I restart a program based on user input?

python – How do I restart a program based on user input?

This line will unconditionally restart the running program from scratch:

os.execl(sys.executable, sys.executable, *sys.argv)

One of its advantage compared to the remaining suggestions so far is that the program itself will be read again.

This can be useful if, for example, you are modifying its code in another window.

Try this:

while True:
    # main program
    while True:
        answer = str(input(Run again? (y/n): ))
        if answer in (y, n):
            break
        print(invalid input.)
    if answer == y:
        continue
    else:
        print(Goodbye)
        break

The inner while loop loops until the input is either y or n. If the input is y, the while loop starts again (continue keyword skips the remaining code and goes straight to the next iteration). If the input is n, the program ends.

python – How do I restart a program based on user input?

Using one while loop:

In [1]: start = 1
   ...: 
   ...: while True:
   ...:     if start != 1:        
   ...:         do_run = raw_input(Restart?  y/n:)
   ...:         if do_run == y:
   ...:             pass
   ...:         elif do_run == n:
   ...:             break
   ...:         else: 
   ...:             print Invalid input
   ...:             continue
   ...: 
   ...:     print Doing stuff!!!
   ...: 
   ...:     if start == 1:
   ...:         start = 0
   ...:         
Doing stuff!!!

Restart?  y/n:y
Doing stuff!!!

Restart?  y/n:f
Invalid input

Restart?  y/n:n

In [2]:

Leave a Reply

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