How do I restart a program based on user input?

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.

Leave a Comment