Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

Python - would you like to play again error

  • 02-11-2014 10:22AM
    #1
    Registered Users, Registered Users 2 Posts: 15,805 ✭✭✭✭


    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.


Comments

  • Moderators, Computer Games Moderators Posts: 4,282 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, Registered Users 2 Posts: 15,805 ✭✭✭✭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 !


Advertisement