如何解决名称错误:未定义名称'xx'?



我正在学习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/oliver/Desktop/test.py", line 22, in <module>
choice=input(pr).strip()[0].lower()
NameError: name 'pr' is not defined

你的代码中有两个错误,

  1. showmenu方法中的逻辑需要缩进
  2. _name_=='_main_'->__name__ == "__main__"
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()

最新更新