我在学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
您的代码中有两个错误,
showmenu
需要缩进_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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句