Python 3.x 有人能无误地重新编写这段代码吗

Python 3.x 有人能无误地重新编写这段代码吗,python-3.x,Python 3.x,我用python 3.5编写了这段代码 temp=0 def add1(x): f=12 if temp < x: for i in range(20): temp=temp + f print(temp) add1(21) Traceback (most recent call last): File "<pyshell#29>", line 1, in <module>

我用python 3.5编写了这段代码

temp=0
def add1(x):
    f=12
    if temp < x:
        for i in range(20):
            temp=temp + f
            print(temp)
add1(21)


Traceback (most recent call last):   File "<pyshell#29>", line 1, in
 <module>
     add1(12)   File "<pyshell#28>", line 3, in add1
     if temp < x: UnboundLocalError: local variable 'temp' referenced before assignment
temp=0
def add1(x):
f=12
如果温度
似乎您的意思是将
temp
作为
add1
中的局部变量:

def add1(x):
    temp=0 # Here!
    f=12
    if temp < x:
        for i in range(20):
            temp=temp + f
            print(temp)
def add1(x):
温度=0#这里!
f=12
如果温度
您应该将
temp
变量作为参数传递到函数中,以便它可以正确使用和修改,而不会产生任何错误。此外,为全局变量和函数参数使用不同的名称也是一种很好的做法。您的代码应该如下所示:

tempglobal=0

def add1(x, tempparam):
    f=12
    if tempparam< x:
        for i in range(20):
            tempparam=tempparam+ f
            print(tempparam)

add1(21, tempglobal)
tempglobal=0
def add1(x,临时参数):
f=12
如果tempparam