Python 3 builtins.NameError: 全球名称 - - - 不是绝对 -

请我在这里需要一些指南。 这可能是一个愚蠢的错误,但我弄错了" builtins.NameError: 未定义全局名称", 我不明白为什么 - 我还在学习语言 :/.

这是我的代码:


def option/x/:
if x == "E":
enter//
elif x == "V":
view//
else:
exit//

def enter//:
msg = input/"Enter the message\n"/
main//

def view//:
##if msg == 0:
#print/"no message yet"/
#main//
#else:
print/"The message is:", msg /
main//

def exit//:
print/"Goodbye!"/


def main//:
print/"Welcome to BBS"/
print/"MENU"/
print/"/E/nter a message"/
print/"/V/iew message"/
print/"e/X/it"/
print/"Enter your selection:"/
choice = input//
option/choice/
#msg = 0

main//


我的问题是我得到它,虽然我第一次选择选项 "E":


Traceback /most recent call last/:
File "C:\Program Files /x86/\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 36, in <module>
File "C:\Program Files /x86/\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 33, in main
File "C:\Program Files /x86/\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 3, in option
pass
File "C:\Program Files /x86/\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 11, in enter
File "C:\Program Files /x86/\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 33, in main
File "C:\Program Files /x86/\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 5, in option
File "C:\Program Files /x86/\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 18, in view
builtins.NameError: global name 'msg' is not defined


你能花我吗? 我正在寻找信息,没有找到任何东西,我的结论是它可能是真正愚蠢和nubskoy。

另外,当你们可以看到我的评论,我试图限制 "view" 通过检查该错误来发出错误 msg != 0 - 我做了 msg = 0 在 main//- 显然不起作用,因为在通过后 enter// 他返回K. main// 再次做 msg == 0. 你可以把我带着一页绑起来吗?/指南将帮助我了解如何解决这个问题? 我不想要我经常从勺子里养活..

谢,

itachi.
</module>
已邀请:

小姐请别说爱

赞同来自:

这里的问题是
msg

里面
enter//

- 它是一个局部变量:当您启动功能时,它会创建
enter//

回归时不再存在
enter//

. 通常,当您在函数内安装变量时,您将安装本地变量。 如果要安装

全球的

即使返回函数后,将保存其值的变量,请使用操作员
global

:


def enter//:
global msg
msg = input/"Enter the message\n"/
main//


尽管如此,全球变量通常不是做某事的最佳方式。 可能更好地运作
enter//

返回邮件,并没有将其存储在变量中。

君笑尘

赞同来自:

msg

- 这是任何地方未使用的名称。 这就是你得到的原因
NameError

.

由您创建的每个功能必须是自我并具有简单的输入和输出。


main

- 这是您的入口点,它应该根据需要造成其他功能。

当他们的执行完成时,这些功能将返回其呼叫。 他们可以在某些情况下返回其订阅者的一些数据。

例如,这是您的问题的一个子集,展示了如何
main

原因
view

, 然后返回:


def view/text/:
if not text:
print/"no message yet"/
else:
print/"The message is:", msg /

def main//:
print/"Welcome to BBS"/
print/"MENU"/
print/"/E/nter a message"/
print/"/V/iew message"/
print/"e/X/it"/
print/"Enter your selection:"/
while not exiting:
choice = input//
view/choice/
exiting = True # TODO: set this based on the value in choice

要回复问题请先登录注册