关于python:while循环检查有效的用户输入?

While loop to check for valid user input?

本问题已经有最佳答案,请猛点这里访问。

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

(使用python2.7)

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

1
2
3
4
5
6
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

以上内容打印到控制台:

1
2
3
4
5
6
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运算符。


你可以使用这个条件

1
2
3
4
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:")

较短的解决方案

1
2
while raw_input("Enjoying the course? (y/n)") not in ('y', 'n'):
    print("Sorry, I didn't catch that. Enter again:")

你的代码做错了什么

关于您的代码,您可以按如下方式添加一些打印:

1
2
3
4
5
6
7
8
9
10
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

上面打印出来:

1
2
3
4
5
6
7
8
9
10
11
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运算符,则应编码:

1
2
3
4
5
6
7
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

然而,在我看来,赛博的解决方案和我较短的解决方案都更优雅(即,更多的Python)。


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

1
2
3
4
5
6
7
8
9
10
11
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='--,那么继续执行循环如果该选项有任何值,则继续进入循环体并检查特定输入的值,如果输入不满足要求的值然后再次将选项变量重置为假值以继续提示用户直到提供正确的输入