[英]Why this Python code can't print out global variable outside of it's function
我知道b
是局部变量。 但是c
是全局变量。 为什么我不能在 function 之外打印出来?
a = 5
def func():
b = 8
global c
c = 9
print(a)
# print(b)
print(c) # line 10
Output
c:\Users\test>py script.py
5
Traceback (most recent call last):
File "script.py", line 10, in <module>
print(c)
NameError: name 'c' is not defined
c:\Users\test>
即使您定义了func()
,也不会在代码中的任何地方调用/调用。 因此,全局变量c
不会在运行时定义。
print(a)
# print(b)
func() # without this, the variable won't be defined in the runtime.
print(c)
程序在到达变量之前无法定义变量,要到达 c,您必须调用 func。
您需要先调用func
,否则将永远不会定义global c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.