Search code examples
pythondice

Very basic python


Getting an error but I don't know why..(I'm learning) My code;

import random
input("Hit enter to roll the dice")
global answer
def rollDice():
    result = random.randrange(1,6)
    print ("It landed on.." + str(result))
    answer = input("would you like to play again? [y/n]")
rollDice();


if (answer == "y" or "Y"):
    rollDice();

Error; (some of the script works)

Hit enter to roll the dice
It landed on..5
would you like to play again? [y/n]y
Traceback (most recent call last):
  File "diceRoller.py", line 11, in <module>
    while (answer == "y" or "Y"):
NameError: name 'answer' is not defined

Solution

  • On top of what the answers are saying, I would advise you not to use global, instead I would return whether the person wanted to continue or not, and continue based off that, for example:

    import random
    input("Hit enter to roll the dice")
    def rollDice():
        result = random.randrange(1,6)
        print("It landed on.. " + str(result))
        answer = input("Would you like to play again? [y/n]")
        if answer in ("y", "Y"):
            return True
        return False
    
    while rollDice():
        continue
    

    Also, use a loop instead of an if statement. Otherwise you won't be able to ask the user if he/she wants to continue indefinitely.