且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-26 10:44:46

更短的解决方案

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

你的代码做错了什么

关于你的代码,你可以添加一些打印如下:

What your code is doing wrong

With regard to your code, you can add some print as follow:

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 的值.这就是你做错了.

As you can see, there is a first step in your code where the question appears and your answer initializes the value of choice. This is what you are doing wrong.

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

If you have to use both the != operator and the loop_condition then you should code:

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​​ 的解决方案和我更短的解决方案都更优雅(即更 Python 化).

However, it seems to me that both Cyber's solution and my shorter solution are more elegant (i.e. more pythonic).