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

时间:2015-05-15 19:33:34

标签: 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 the course? (y/n)'):
        print("Sorry, I didn't catch that. Enter again: ")
    else:
        student_surveyPromptOn = False 

以上打印到控制台:

Enjoying the course? (y/n) y
Enjoying the course? (y/n) n
Sorry, I didn't catch that. Enter again: 
Enjoying the course? (y/n) x
Sorry, I didn't catch that. Enter again: 
Enjoying the course? (y/n)  

这显然是不正确的 - 当用户输入'y'或'n'时循环应该结束但我不知道如何做到这一点。我在这做错了什么?

注意:挑战要求我同时使用!=运算符和loop_condition

3 个答案:

答案 0 :(得分:6)

您可以使用条件

$.cookie.json = true;
$.cookie("previousObject", savedObjs);

答案 1 :(得分:1)

更短的解决方案

while raw_input("Enjoying the course? (y/n) ") not in ('y', 'n'):
    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

以上打印出来:

Enjoying the course? (y/n) y
choice = y
Enjoying the course? (y/n) n
choice = y
input = n
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n) x
choice = y
input = x
Sorry, I didn't catch that. Enter again:
Enjoying the course? (y/n) 

正如您所看到的,代码中的第一步是出现问题并且您的答案初始化choice的值。这就是你做错了。

!=loop_condition

的解决方案

如果您必须同时使用!=运算符和loop_condition,那么您应该编码:

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)。

答案 2 :(得分:0)

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

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=""

条件语句的意思是,只要 choice 变量为false - 没有任何值意味着 choice ='' - ,然后继续#with循环 如果选项具有任何值,则继续进入循环体并检查 如果输入未满足所需值,则为特定输入的值 然后再次将选择变量重置为False值以继续提示用户 直到提供正确的输入

相关问题