【问题标题】:Why this Python code can't print out global variable outside of it's function为什么这个 Python 代码不能在它的函数之外打印出全局变量
【发布时间】:2020-04-16 02:15:48
【问题描述】:

我知道b 是局部变量。 但是c 是全局变量。为什么我不能在它的功能之外打印出来?

a = 5

def func():
    b = 8
    global c
    c = 9

print(a)
# print(b)
print(c)        # line 10

输出

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>

【问题讨论】:

  • 你从来没有调用过这个函数。

标签: python python-3.x global-variables


【解决方案1】:

即使您定义了func(),它也不会在代码中的任何地方调用/调用。所以,全局变量c 不会在运行时定义。

print(a)
# print(b)
func() # without this, the variable won't be defined in the runtime.
print(c) 

程序在到达变量之前不能定义变量,要到达 c 你必须调用 func。

【讨论】:

    【解决方案2】:

    你需要先调用func,否则global c永远不会被定义

    【讨论】:

      猜你喜欢
      • 2016-04-01
      • 2020-08-07
      • 1970-01-01
      • 2017-03-03
      • 1970-01-01
      • 2010-12-03
      • 2012-12-17
      • 2018-11-12
      • 2016-01-17
      相关资源
      最近更新 更多