较短的解决方案
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 = Truewhile 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) ychoice = yEnjoying the course? (y/n) nchoice = yinput = nSorry, I didn't catch that. Enter again:Enjoying the course? (y/n) xchoice = yinput = xSorry, I didn't catch that. Enter again:Enjoying the course? (y/n)
如您所见,代码中的第一步是出现问题,答案将初始化的值
choice。这就是你做错了。
一个解决方案!=
,并loop_condition
如果必须同时使用
!=运算符和,
loop_condition则应编写代码:
student_surveypromptOn = Truewhile 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化)。



