我怎样才能在函数之外看到它?

问题描述 投票:0回答:0
import random
guesses = 3

def playernumber(guess):
    if guess in range(1,10):
        print("passed")
    else:
        print("Input invalid. Try again: ")
            
def main():
    computernumber = random.randint(1,10)
    playernumber(int(input(f"I'm thinking of a number 1-10. {guesses} chances to guess remaining: ")))
    if guess == computernumber:
        print(f"The answer is {computernumber}. You win! ")
    else:
        print(f"Incorrect. {guesses} chances remaining: ")
main()

我正在编写一个数字猜测器作为初学者项目,以帮助我理解 Python 中的函数参数。我相信我知道问题是什么:(变量“guess”只能在 playernumber() 函数中看到,但我试图在 main() 函数中调用它)而且我不确定如何修复它。帮忙吗?

错误! 追溯(最近一次通话): 文件“”,第 18 行,位于 文件“”,第 12 行,在 main UnboundLocalError:无法访问与值无关的局部变量“猜测”

这是错误,我什至不确定为什么它引用调用 main() 的那一行,所以我不确定如何解决这个问题。

python scope
© www.soinside.com 2019 - 2024. All rights reserved.