Python:确保字符串是用户的有效输入,并拒绝任何其他输入

尝试配置我的程序,使其仅在整个程序中接受“是”和“否”的答案,并且任何其他输入(例如整数和其他字符串)都会产生错误消息。使用 .isalpha() 也不适合我,任何有关如何帮助编写代码的提示将不胜感激。


text = True


    if text:

        textHelp = input('Are you sleeping? '.isalpha())

        if textHelp == 'yes':

            print('Cannot take phone call b/c im sleeping')

        else:

            print('Can take phone call)


慕侠2389804
浏览 48回答 3
3回答

慕工程0101907

根据您的描述,您要寻找的是这样的:input_text = input('Are you sleeping? ').lower()if input_text == 'yes':  print('Cannot take phone call b/c im sleeping')elif input_text == 'no':  print('Can take phone call')else:  print('Expected a yes or a no for an answer')Thr.lower()方法确保“Yes”、“yes”、“yEs”等得到相同的处理。您不需要.isalpha()此场景的方法。

杨魅力

我想这就是您正在寻找的。while true:    textHelp = input('Are you sleeping? ')    if textHelp.isalpha():        # your expected output ...        break    else:        print("try again!")

慕无忌1623718

您可以尝试使用 if..elif..else:if textHelp == 'yes':    print('Cannot take phone call b/c im sleeping')elif textHelp == 'no':    print('Can take phone call')else:   print("Faulty message")如果您想在无效输入时保持提示继续:while True:  if textHelp == 'yes':    print('Cannot take phone call b/c im sleeping')    break  elif textHelp == 'no':    print('Can take phone call')    break  else:   print("Faulty message")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python