繁体   English   中英

为什么这个 Python 代码无法打印出 function 之外的全局变量

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM