我正在努力在多个函数中使用变量(赋值之前引用了变量!)

Jam*_*mie 1 python variables python-2.7

我是Python的新手,真的很喜欢代码。我正在尝试重新创建一个我的朋友在Python中制作的人口模拟器。这真的很基础,目前仅使用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()
Run Code Online (Sandbox Code Playgroud)

我正在代码学院学习Python,并使用Python版本2.7.2在他们的实验室测试我的代码。Int是我的智力变量,intel是我的智力增加功能名称。我想知道为什么我在调用int()函数时得到“分配前引用的局部变量'int'”错误,以及如何修复它并能够在多个函数中使用我的变量。我只想修改int变量并将其增加3,并在另一个函数中执行类似的操作。请记住,我只有15岁,所以请尝试简化您的回答,以使我理解,因为在搜索解决方案时,我发现很多东西会令人困惑。我尚未创建选项A函数,但是它将具有相似的属性。

编辑:谢谢你们的快速反应。我现在知道了。真的有帮助!

Mar*_*nen 5

pop并且int在任何函数之外分配,并称为全局变量。在函数内部分配的变量称为局部变量。要在函数内部分配全局变量,必须先将其声明为全局变量:

def intel():
    global int
    int = int + 3
Run Code Online (Sandbox Code Playgroud)

请注意,这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
Run Code Online (Sandbox Code Playgroud)

这称为阴影内建函数,应避免。使用其他变量名。