函数中的变量错误

Variable error in function

我想做一个猜数字游戏,我写了这段代码:

from random import randint as rand

number=rand(-1,1001)
tries=0
def numguess():
    guess=int(input("The chosen number is between 0 to 1000.\nEnter your guess : "))
    tries=tries+1    
numguess()

while True:
    if number==guess:
        print ("You won. My number was effectively" ,number,". \n It took you ",tries, "to guess the number.")
        break 

    elif number<guess:
        print ("The number I chose is lower than your guess")
        numguess()

    else:
        print ("The number I chose is higher than your guess")
        numguess()

当我 运行 它时,它要求我输入然后引发 UnboundLocalError。我做错了什么吗?我试着搜索但我不明白。谢谢。

您的 tries 变量在本地处理 - 因为您为其赋值,所以使用:

global tries
tries = tries +1

在你的函数中