繁体   English   中英

如何解决 python 的 NameError: name 'xx' is not defined?

[英]How to solve python's NameError: name 'xx' is not defined?

我在学python,按照书中代码写的逻辑,想看运行结果,代码如下,但是输出错误NameError: name 'pr' is not defined

代码显示如下:

stack=[]
def pushit():
    stack:append(input(' Enter New String: ').strip())
def popit():
    if len(stack)==0:
        print('Cannot pop from an empty stack!')
    else:
        print ('Removes [','stack.pop()',']')
def viewstack():
    print(stack)
CMDs={'u':pushit,'o':popit,'v':viewstack}
def showmenu():
    pr=''' 
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice:'''
while True:
    while True:
        try:
            choice=input(pr).strip()[0].lower()
        except (EOFError,KeyboardInterrupt,IndexError):
            choice='q'
        print('\nYou picked:[%s]'%choice)
        if choice not in 'uovq':
            print('Invalid option,try again')
        else:
            break
        if choice=='q':
            break
        CMDs[choice]()
if _name_=='_main_':
    showmenu()

错误信息如下:

Traceback (most recent call last):
  File "/Users/zego/Desktop/test.py", line 22, in <module>
    choice=input(pr).strip()[0].lower()
NameError: name 'pr' is not defined

您尚未在右侧索引处插入showmenu功能代码。 while循环应该从前面的one tab空间开始。

看看下面的代码。

stack=[]
def pushit():
    stack:append(input(' Enter New String: ').strip())
def popit():
    if len(stack)==0:
        print('Cannot pop from an empty stack!')
    else:
        print ('Removes [','stack.pop()',']')
def viewstack():
    print(stack)
CMDs={'u':pushit,'o':popit,'v':viewstack}
def showmenu():
    pr=''' 
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice:'''
    while True:
        while True:
            try:
                choice=input(pr).strip()[0].lower()
            except (EOFError,KeyboardInterrupt,IndexError):
                choice='q'
            print('\nYou picked:[%s]'%choice)
            if choice not in 'uovq':
                print('Invalid option,try again')
            else:
                break
            if choice=='q':
                break
            CMDs[choice]()

暂无
暂无

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

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