为什么这段代码出错了?
D 不是全局变量吗?
import pandas as pd
D = pd.DataFrame()
D['z'] = [2]
def funz2(z):
d = pd.DataFrame()
d['z'] = z
D = D.append(d)
print(D)
print(funz2(4))
这是错误信息。
In [22]: ---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-22-68bb930462f5> in <module>()
----> 1 __pyfile = open('''/tmp/py3865JSV''');exec(compile(__pyfile.read(), '''/home/donbeo/Desktop/prova.py''', 'exec'));__pyfile.close()
/home/donbeo/Desktop/prova.py in <module>()
14
15
---> 16 print(funz2(4))
/home/donbeo/Desktop/prova.py in funz2(z)
10 d = pd.DataFrame()
11 d['z'] = z
---> 12 D = D.append(d)
13 print(D)
14
UnboundLocalError: local variable 'D' referenced before assignment
编辑: 如果变量不是自动全局的。 为什么它可以工作?
x = 3
def funz(z):
return z * x
print(funz(4))