我有这个代码:
def r():
i += 1
return i
def f():
return x*a
i = 0
a=2
x=3
print f()
print r()
我收到此错误r()
,但不是f()
:
~$ python ~/dev/python/inf1100/test.py
6
Traceback (most recent call last):
File "/home/marius/dev/python/inf1100/test.py", line 18, in <module>
print r()
File "/home/marius/dev/python/inf1100/test.py", line 2, in r
i += 1
UnboundLocalError: local variable 'i' referenced before assignment
为什么可以f()
使用在函数外部定义的变量,而r()
不能?