如何减少游戏中剩余的尝试次数?

2024-09-30 03:25:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图限制一个人在猜测随机数时的尝试次数。当我运行程序时,我得到了这个错误代码,但我不知道下一步该怎么做。你知道吗

Traceback (most recent call last):
  File "C:/Python27/coding/Guess.py", line 34, in <module>
    main()
  File "C:/Python27/coding/Guess.py", line 24, in main
    trys(userGuess)
  File "C:/Python27/coding/Guess.py", line 29, in trys
    trysLeft -= 1
UnboundLocalError: local variable 'trysLeft' referenced before assignment

代码:

import random    

def main():

    print "Guess a number between 1 and 100."
    randomNumber = random.randint(1,100)
    found = False
    trysLeft = 5

    while not found:

        userGuess = input("Your guess: ")  
        if userGuess == randomNumber:
             print "You got it!"
             found = True

        elif userGuess > randomNumber:
            trys()
            print "Guess lower!"

        else:
            trys()
            print "Guess higher!"

def trys():

    trysLeft -= 1
    print "You have %d trys left." %trysLeft


if __name__ == "__main__":
    main()

Tags: inpymainlinerandomfilepython27print
3条回答

有3个选项可以解决此问题:

  • 把trysLeft放在全局(不是个好主意)
  • 将函数trys()添加到类中并将其引用为自我尝试离开你知道吗
  • 将变量传递到trys()函数中。你知道吗

问题是您在函数中分配trysLeft,因此它假定它具有局部(而不是全局)作用域。但实际上您需要分配全局变量,因此需要声明trysLeft具有全局作用域。将trys()函数更改为:

def trys():
    global trysLeft
    trysLeft -= 1
    print "You have %d trys left." %trysLeft

有关更多信息,请参见FAQ

FWIW,解决这个问题的正确方法是将变量传递给函数,而不是使用全局变量,但这超出了问题的范围。你知道吗

您需要将trysLeft传递给函数,它才能看到它。。。你知道吗

    def trys(trysLeft):
        trysLeft -= 1
        print "You have %d trys left." %trysLeft
        return trysLeft

当你打电话给trys。。。你知道吗

trysLeft = trys(trysLeft)

相关问题 更多 >

    热门问题