How to Restart a Program Based on User Input

How do I restart the program based on user input?

Simply make it a while loop and check whether the answer is yes or no.

while input("Continue?: ") == "y":
... rest of code

This way it will continue looping for as long as the input is "y" (yes). Put your other input in the "rest of code" bracket, so it asks again for the user input.

To make your coding experience easier, I suggest you read about while loops and input. The while loop will keep on executing for as long as the condition is met. In the above condition, for as long as the user input is "y". You should run the other "input" inside of your while loop, so it won't start an infinite loop (either way, it'd end on your "n", or any other input, for as long as it isn't "y").

Full code:

while input("Would you like to play? (Y/n): ") == "Y":
choice = input("Rock, Paper, or Scissors? ")

if choice == "Rock" or choice == "rock":
print("I choose Paper! \nI win!")

if choice == "Paper":
print("I choose Scissors! \nI win!")

if choice == "Scissors":
print("I choose Rock! \nI win!")

if choice == "rock":
print("I choose Paper! \nI win!")

if choice == "paper":
print("I choose Scissors! \nI win!")

if choice == "scissors":
print("I choose Rock! \nI win!")

In comparison to the other solutions, this will also ask on the first try.

How can I get my code to restart based on user input?

Wrap your logic in a function.
then call the function in your if statement.

def getWeight(name):
print("Nice to meet you, " + name)

js = input("What is your weight you would like to convert from lbs
to kg? ")

weight1 = int(js) * 0.453592
weight2 = str(weight1)
return weight2

if y:
getWeight(name)

Restart Python program if user input to 'run again?' is 'y'

As @burhan suggested, simply wrap your main program inside a function. BTW, your code has some bugs which could use some help:

  • if answer in y, n: - you probably mean if answer not in ('y', 'n'):
  • number = (" ") is an irrelevant line
  • while True makes no sense in your main program
  • print("Invalid input.") is below a break, thus it'll never be executed

So you'll have something like:

def main():
total = 0

num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3

if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)

while True:
answer = raw_input("Run again? (y/n): ")
if answer not in ('y', 'n'):
print("Invalid input.")
break
if answer == 'y':
main()
else:
print("Goodbye")
break


Related Topics



Leave a reply



Submit