Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Python - would you like to play again error

Options
  • 02-11-2014 11:22am
    #1
    Registered Users Posts: 15,335 ✭✭✭✭


    I'm very new to Python and am struggling to figure out how get it to handle wrong input.
    I want to end the code with a question do you want to play again y/n ?
    However I can't figure out how to handle if the user doesn't answer y or n
    So my overall code looks like
    while True:
    .
    <code>
    .
       restart = input("Would you like to play again y/n?\n")
       if restart == "n":
         break
    print ("Goodbye", playername)
    

    I've tried putting:
     elif restart != "y":
     restart = input("Ups looks like you didn't enter a valid answer, please enter y or n")
    
    But its not working, really hoping someone can help here!

    Thanks.

    Have a weather station?, why not join the Ireland Weather Network - http://irelandweather.eu/



Comments

  • Moderators, Computer Games Moderators Posts: 4,281 Mod ✭✭✭✭deconduo


    You're pretty close. What you need is for the valid answer test to be in a while loop as well. For example:
    while True:
        print("Playing the game")
        restart = input("Would you like to play again y/n?\n")
        while restart not in ("y", "n"):
            restart = input("Ups looks like you didn't enter a valid answer, please enter y or n\n")
        if restart == "n":
            break
            print ("Goodbye")
    

    This way it keeps checking for restart to either be 'y' or 'n', and won't break out of the loop until that condition is true.


  • Registered Users Posts: 15,335 ✭✭✭✭Supercell


    deconduo, If i could give you a million thanks I would!!, it works great :D
    This had me driven to distraction!, I had tried a while loop but was trying it with "y" or "n" , i hadn't come across 'not in' yet
    Thanks again !

    Have a weather station?, why not join the Ireland Weather Network - http://irelandweather.eu/



Advertisement