在python中rando猜谜游戏

时间:2016-04-07 02:14:41

标签: function python-3.x random

我的代码工作正常。如果我没有使用该功能,那么程序应该如何工作。当我有这个功能时,它告诉我没有定义变量号。我尝试将变量定义为0或1,但最终我的数字为0或1.请记住,这是针对学校的。建议会有所帮助,谢谢!

import random

easy = random.randint (1,20)
medium = random.randint (1,50)
hard = random.randint (1,100)
guessesTaken = 0

name = input("Hello, What is your name? ")

def difficulties():
    difficulty = input("Well, ",name,". What dificulty would you like ?       easy, medium, or hard? ")
    if difficulty == "easy":
        number = easy
        print ("Okay, ",name,". I am thinking of a number between 1 and 20")
    if difficulty == "medium":
        number = medium
        print ("Okay, ",name,". I am thinking of a number between 1 and 50")
    if difficulty == "hard":
        number = hard
        print ("Okay, ",name,". I am thinking of a number between 1 and  100")

difficulties()

while guessesTaken < 6:
    guess = int(input('Take a guess. ')) 
    guessesTaken = guessesTaken + 1

    if guess < number:
        print("Your guess is too low.") 

    if guess > number:
        print("Your guess is too high.")

    if guess == number:
        break

if guess == number:
    guessesTaken = str (guessesTaken)
    print("Good job, ",name," ! You guessed my number in ",guessesTaken," guesses, good job!")

if guess != number:
    number = str (number)
    print("Nope. The number I was thinking of was ",number,", better luck next time!")

1 个答案:

答案 0 :(得分:0)

它说number未定义的原因是因为它是difficulties()的局部变量。要解决此问题,请在difficulties()函数中输入difficulty后,输入

global number

这使number成为global变量,允许在difficulties()函数之外引用它。 希望这有帮助!