简体   繁体   English

为什么我在 function 中的全局值在打印时返回错误?

[英]Why is my global value in a function return an error when i print it?

def name():
    global x
    x = "Hello"
    print(x + " Guys!")

print(x)
print(name())

the output is output 是

NameError: name 'x' is not defined

Why is this happening?为什么会这样? This is weird because I placed the (global) function.这很奇怪,因为我放置了(全局)function。

The first time print(x) is called outside the function, the function not having been run yet, x is not defined.第一次在 function 之外调用 print(x),function 尚未运行,x 未定义。 Once you run name(), then you can print(x) whenever you like.一旦你运行了 name(),你就可以随时打印(x)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的 function 有“返回”,当我打印时仍然得到“无” - My function have "return" and still getting "None" when I print 为什么我的打印功能出现语法错误? - Why do I have a syntax error on my print function? 为什么我的打印功能出现语法错误 - why am i getting a syntax error on my print function 为什么在函数中使用print语句时赋值语句产生值而使用return时没有值? - why does assignment statement produces a value when print statement is used in function and no value when return is used? 我如何获得__str __()函数的返回值以在我的main中打印? - How do I get the return value of my __str__() function to print in my main? Python:为什么我运行代码时字符串不返回或不打印 - Python: why doesn't my string return or print when I run my code 我正在尝试为我正在开发的应用程序制作 GUI,但是当我尝试打印全局变量时出现错误。 为什么? - I am trying to make a GUI for a app I am working on but when I try print a global variable I get an error. Why? “打印”功能的返回值? - Return value of 'print' function? 无论如何要更改我的递归函数以返回值并且没有全局变量? - Anyway to change my recursive function to return a value and be without global variables? 如何将 function 的本地值返回到我的全局列表? - How to return the local value of a function to my global list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM