-1

I'm a little confused on how to allow the user to retry entering something in Python. I created an example code bellow. I want it so if the user types a invalid answer other than 1 or 2 it allows them to try again.

import sys

def start():
    print "Hello whats your name?"
    username = raw_input("> ")
    print "Okay, welcome to the game %s" % username
    print "Do you want to hear the background of the game?"
    print "1. Yes"
    print "2. No"

    background = raw_input("> ")

    if background == "1":
            print "Background goes here."

    elif background == "2":
        print "Background skipped"
start()

How would I incorporate a try again option into this example? Thanks!

  • 1
    You will need to wrap the code that you want to repeat in a loop. Then just break out of the loop if the input is 1 or 2. – Reticulated Spline Dec 06 '14 at 05:35
  • possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – jonrsharpe Dec 07 '14 at 09:15

1 Answers1

1

Use a while loop:

def start():
    print "Hello whats your name?"
    username = raw_input("> ")
    print "Okay, welcome to the game %s" % username
    print "Do you want to hear the background of the game?"
    print "1. Yes"
    print "2. No"
    while True:                            # Repeat the following block of code infinitely
        background = raw_input("> ")

        if background == "1":
            print "Background goes here."
            break                            # Break out of loop if we get valid input
        elif background == "2":
            print "Background skipped"
            break                            # Break out of loop if we get valid input
        else:
            print "Invalid input. Please enter either '1' or '2'"   # From here, program jumps back to the beginning of the loop

start()
rfj001
  • 7,948
  • 8
  • 30
  • 48