我正在寻找一种实现“按Y继续,N取消”提示的方法。
我目前的实现方式是
Prompt = None
while Prompt not in ("yes", "y", "n", "no"): #loop until the user inputs a valid answer
Prompt = input("Do you wish to continue? answer y or n\n")
if Prompt == 'y' or == 'yes':
state = 2 # switch state to processing state
elif Prompt == 'n' or == 'no': #cancel
break
有没有更有效的方法来实现此提示?
是,只需尝试以下方法。
while True:
Prompt = input("Do you wish to continue? answer y or n\n")
if Prompt in ['y', 'yes']:
state = 2 # switch state to processing state
elif Prompt in ['n', 'no']:
break
您的代码看起来不对,也许我可以帮忙。试试我的代码
Prompt = None
while Prompt not in ("yes", "y", "n", "no"): #loop until the user inputs a valid answer
Prompt = input("Do you wish to continue? answer y or n\n")
if Prompt in ('y', 'yes'):
state = 2 # switch state to processing state
elif Prompt in ('n', 'no'): #cancel
break
Prompt == 'y' or == 'yes'
和Prompt == 'n' or == 'no':
行不正确,因为它应该是Prompt == 'y' or Prompt == 'yes'
和Prompt == 'n' or Prompt == 'no'
。但我更喜欢使用in
运算符
对此无效的是什么?
您可以通过很多方式重新输入此代码,但是它们都与效率无关。更大的问题是,为什么您甚至对此感到担忧。
[不要为使事情变得高效而迷失方向,特别是如果您是初学者。编程不像历史类,在该类中始终必须找到正确的答案。编程是一种类似于铅笔的工具,可用于记录“历史记录”类中的答案。书写时有很多握住铅笔的方法。
编辑
[如果您有多个提示的情况,您可以考虑摆脱if语句,并建立一个像字典一样的接口,该接口将每个用户的提示响应映射到处理该特定提示的功能,像
def PrintHello():
print('Hello')
LookUpFunction = {'hello':PrintHello}
def HandleUser():
try:
return LookUpFunction[input('What would you like to do ? ')]
except KeyError:
return None
while True:
func = HandleUser()
if(func):
func()
break
您也可以只创建作为用户提供的输入字符串的名称别名的函数,然后使用locals
或globals
调用此函数。
def c_hello():
print('Hello There')
def c_quit():
print('Goodbye')
command = locals()['c_'+input('What would you like? ')]
command()
因此在这两种情况下,您要做的就是提供处理特定提示的功能