2017-05-14 30 views
0

我在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 

回答

1

好像你的意思temp在里面add1一个局部变量:

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

你应该通过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) 
相关问题