Skip to main content
 首页 » 编程设计

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

2025年05月04日16yxwkf

我正在尝试重建一个人口模拟器。它非常基础,目前只使用 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() 函数时。如何修复它以便我能够在多个函数中使用我的变量?

请您参考如下方法:

pop 和 int 在任何函数之外赋值,称为全局变量。在函数内部分配的变量称为局部变量。要在函数内分配一个全局变量,必须首先声明它是全局的:

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 

这称为阴影内置,应该避免。使用不同的变量名。