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