有验证和重新启动选项的用户回答是还是否?

2024-10-02 04:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

(py)目前,当用户输入“y”和“n”两个选项之外的内容时,下面的代码不会验证/输出错误消息,因为它处于while循环中。在

again2=input("Would you like to calculate another GTIN-8 code? Type 'y' for Yes and 'n' for No. ").lower() #**

    while again2 == "y":
        print("\nOK! Thanks for using this GTIN-8 calculator!\n\n")
        restart2()
        break                                                                                                                    #Break ends the while loop

restart2()

我正在努力想办法,当他们输入任何一个给定的选择时,我能用一个输出来回应。例如:

^{pr2}$

因此,当用户的输入不等于“y”或“n”时,程序将返回初始语句并要求用户再次输入。有什么想法仍然支持尽可能少的行的高效代码?谢谢!在


Tags: 代码用户pyyou消息内容forinput
2条回答

递归解决方案:

def get_input():
    ans = input('Y/N? ') #Use raw_input in python2
    if ans.lower() in ('y', 'n'):
        return ans
    else:
        print('Please try again.')
        return get_input()

如果他们真的很顽固,当它达到最大递归深度时就会失败(大约900个错误答案)

def get_choice(prompt="Enter y/n?",choices=["Y","y","n","N"],error="Invalid choice"):
    while True:
        result = input(prompt)
        if result in choices: return result
        print(error)

可能是解决这个问题的一个很好的通用方法

^{pr2}$

你可以粗略地使它不区分大小写。。。或添加其他类型的条件(例如,必须是26到88之间的整数)

相关问题 更多 >

    热门问题