在python中操作函数中的全局变量

2024-10-05 14:29:31 发布

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

好的,如果这个问题之前已经被回答过,我会提前道歉,但是我已经仔细查看了,似乎找不到任何有效的方法。我做了一个非常简单的游戏,你几乎只需要猜一个1到1000之间的数字,如果它是不正确的计算机猜一个数字要么高于或低于你的猜测1。这是我做的一个函数,用来判断猜测是否过低

def numLow(userInput, low, high):
    while userInput < num:
        print ("The guess of {0} is low".format(userInput))
        compGuess = (userInput + 1)
        print ("My guess is {0}".format(compGuess))
        low = (userInput + 1)
        if compGuess < num: 
            print("The guess of {0} is low".format(compGuess))
            userInput = int(input("Enter a value between {0} and 
                         {1}:".format(low, high)))
        else:
            print("The guess of {0} is correct!".format(compGuess))
            print("I WON!!!")
            showTermination()
    return (userInput, low)

现在我的问题是,我想更改全局变量userInput,函数中的low和high。我试过插入

global userInput
global high
global low

在函数之前,但它似乎不起作用,如果我把globals放在函数中,我会得到“name'userInput'is parameter and global”。现在我猜while循环导致了这个问题,但我似乎无法解决它。我完全是新的编码,所以我道歉,如果我打破了任何编码规则或任何东西。谢谢你的帮助。你知道吗


Tags: ofthe函数formatis数字globallow
2条回答

userInput例如,是函数的输入参数。错误消息准确地说明了问题所在。您需要使用一个名为userInput的全局变量,并且有一个名为userInput的输入参数,这对于python来说是两个不同的东西。当userInput应该是全局的时,只需将它定义在全局的某个地方,比如userInput = None,然后不将它作为参数传入函数,只需写入函数global userInput,python就会知道您引用的是全局实例化的变量。两者同时不起作用。你知道吗

像这样使用globals()

globals()['userInput'] = ...

相关问题 更多 >