Python While循环检查有效的用户输入?

Python While循环检查有效的用户输入?,python,while-loop,user-input,Python,While Loop,User Input,这里的Python新手非常抱歉,我确信这是一个愚蠢的问题,但在一个教程中,我似乎无法解决以下挑战,该教程要求我使用while循环来检查有效的用户输入 (使用Python2.7) 这是我的代码,但它工作不正常: choice = raw_input('Enjoying the course? (y/n)') student_surveyPromptOn = True while student_surveyPromptOn: if choice != raw_input('Enjoying

这里的Python新手非常抱歉,我确信这是一个愚蠢的问题,但在一个教程中,我似乎无法解决以下挑战,该教程要求我使用while循环来检查有效的用户输入

(使用Python2.7)

这是我的代码,但它工作不正常:

choice = raw_input('Enjoying the course? (y/n)')
student_surveyPromptOn = True
while student_surveyPromptOn:
    if choice != raw_input('Enjoying the course? (y/n)'):
        print("Sorry, I didn't catch that. Enter again: ")
    else:
        student_surveyPromptOn = False 
上述内容打印到控制台:

喜欢这门课吗?(是/否)是
喜欢这个课程吗?(是/否)否
对不起,我没听清楚。再次输入:
喜欢这个课程吗?(是/否)x
对不起,我没听清楚。再次输入:
喜欢这个课程吗?(是/否)
这显然是不正确的-当用户输入“y”或“n”时,循环应该结束,但我不确定如何做到这一点。我做错了什么


注意:挑战要求我同时使用
=
运算符和
循环\u条件

您可以使用该条件

while choice not in ('y', 'n'):
    choice = raw_input('Enjoying the course? (y/n)')
    if not choice:
        print("Sorry, I didn't catch that. Enter again: ")
较短的解决方案 你的代码做错了什么 关于您的代码,您可以添加一些打印,如下所示:

choice = raw_input("Enjoying the course? (y/n) ")
print("choice = " + choice)
student_surveyPromptOn = True
while student_surveyPromptOn:
    input = raw_input("Enjoying the course? (y/n) ")
    print("input = " + input)
    if choice != input:
        print("Sorry, I didn't catch that. Enter again:")
    else:
        student_surveyPromptOn = False
上面打印出:

喜欢这门课吗?(是/否)是
选择=y
喜欢这个课程吗?(是/否)否
选择=y
输入=n
对不起,我没听清楚。再次输入:
喜欢这个课程吗?(是/否)x
选择=y
输入=x
对不起,我没听清楚。再次输入:
喜欢这个课程吗?(是/否)
如您所见,在代码中有第一步,问题出现,您的答案初始化
选项的值。这就是你做错的地方

具有
的解决方案=
循环\u条件
如果必须同时使用
=运算符和
循环\u条件
然后应编码:

student_surveyPromptOn = True
while student_surveyPromptOn:
    choice = raw_input("Enjoying the course? (y/n) ")
    if choice != 'y' and choice != 'n':
        print("Sorry, I didn't catch that. Enter again:")
    else:
        student_surveyPromptOn = False

然而,在我看来,Cyber的解决方案和我的较短的解决方案都更优雅(即,更具pythonic)。

非常简单的解决方案是在循环开始之前初始化一些变量:

choice=''

#This means that choice is False now

while not choice:
    choice=input("Enjoying the course? (y/n)")
        if choice in ("yn")
            #any set of instructions
        else:
            print("Sorry, I didn't catch that. Enter again: ")
            choice=""
while条件语句的意思是,只要choice变量为false——没有任何值,则表示choice='',然后继续循环 如果选项有任何值,则继续进入循环体并检查 如果输入未满足要求的值,则指定输入的值 然后再次将选择变量重置为False值以继续提示用户
在提供正确的输入之前

谢谢您的帮助!我尝试了解决方法!=和循环_条件,但当用户输入“y”或“n”时,它会再次询问问题。在有人第一次提出问题时输入“y”或“n”后,我如何才能让循环退出?不客气。你在说什么代码?我的
解决方案=
循环\u条件
在有人输入
'y'
'n'
后不会再次询问问题。我想你试过不同的东西。如果是这样,请您编辑您的问题以添加这段代码好吗?
choice=''

#This means that choice is False now

while not choice:
    choice=input("Enjoying the course? (y/n)")
        if choice in ("yn")
            #any set of instructions
        else:
            print("Sorry, I didn't catch that. Enter again: ")
            choice=""