分配错误之前引用的变量 - 如何跨多个函数使用变量?

Variable Referenced before Assignment Error - How to use variables across multiple functions?

我正在尝试重建一个人口模拟器。它非常基础,目前只使用 3 个变量。这是我的代码:

pop = 7000000000
int = 5

#Clear
def cls():
    print "\n" * 80

#Main script
def MS():
    cls()
    print "Population =", pop, "Intelligence =", int
    print ""
    print "Do You:"
    print "A) Increase Population"
    print "B) Increase Intelligence"
    choice = raw_input("Option:")
    if choice == "a" :
        print "option a"
    elif choice == "A" :
        print "option A"
    elif choice == "b" :
        intel()
    elif choice == "B" :
        intel()

#Increase Intelligence
def intel():
    int = int + 3

MS()

Int是我的智力变量,intel是我的智力增加函数名。

我想知道为什么我会收到 :

"local variable 'int' referenced before assignment" Error

当我调用 int() 函数时。如何修复它以便我能够在多个函数中使用我的变量?

Python 中,仅在函数内部引用的变量是隐式全局变量。如果一个变量在函数体内的任何地方被赋予了一个新值,它就被认为是局部的。如果某个变量在函数内部被赋予了新值,则该变量隐式是局部的,您需要将其显式声明为“全局”。

如下所示修改您的 intel()

def intel():
    global int
    int = int + 3

popint 在任何函数外赋值,称为 全局变量 。在函数内部分配的变量称为局部变量。要在函数内赋值给全局变量,必须先声明为全局变量:

def intel():
    global int
    int = int + 3

注意int是Python中类型的名称,不应该用作变量名:这会导致以后出现问题:

>>> int
<type 'int'>
>>> int(5.1)      # this works
5
>>> int=1
>>> int(5.1)      # now it is broken
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

这称为 隐藏内置函数,应避免使用。使用不同的变量名称。