Search code examples
pythonif-statementwhile-loopdice

Dice game query While loop


I am trying to create a dice game using a while loop and if's. I have done this successfully however I am trying to figure out how to program the game so that if numbers 4,6 or 12 are not input it will state invalid choice and will ask diceChoice again. Can anybody help?

So far I have...

rollAgain = "Yes" or "yes" or "y"

while rollAgain == "Yes" or "yes" or "y":
    diceChoice = input ("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?")
    if diceChoice == "4":
        import random 
        print("You rolled a ", random.randint(1,4)) 
    if diceChoice == "6":
        import random
        print("You rolled a ", random.randint(1,6))
    if diceChoice == "12":
        import random
        print("You rolled a ", random.randint(1,12))

    rollAgain = input ("Roll Again?") 
print ("Thank you for playing")

Solution

  • Fixed While Loop, Tidied up all the repetition. Moved import statement to the top. Structured to allow more options for rollAgain and diceChoice.

    import random
    
    rollAgain = "Yes"
    
    while rollAgain in ["Yes" , "yes", "y"]:
        diceChoice = input ("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?")
        if diceChoice in ["4","6","12"]:
            print("You rolled a ",random.randint(1,int(diceChoice)))
        else:
            print "Please input 4,6, or 12."
        rollAgain = input ("Roll Again?") 
    
    print ("Thank you for playing")
    

    Doing this sort of assignment:

    rollAgain = "Yes" or "yes" or "y"
    

    Is unnecessary - only the first value will be inputted. Pick one for this variable; you only need one for its purposes.

    This sort of assignment doesn't work here either:

    while rollAgain == "Yes" or "yes" or "y":
    

    It will again only check the first value. You either have to split it up like other posters have done, or use a different data structure that will incorporate them all like a list in the code above.