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
您可以使用
条件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: ")
较短的解决方案
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的解决方案和我的更短的解决方案都更优雅(即更python化)。
非常简单的解决方案是在循环开始之前初始化一些变量:
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值以继续提示用户直到提供正确的输入