繁体   English   中英

使用 While 循环处理多个条件/异常

[英]Multiple Conditions/Exception Handling using a While Loop

我正在尝试制作一个接受特定输入的 while 循环,但如果输入与条件不匹配,则要求用户重新提交。 但是,在添加了 while 循环之后,输入一个输入只会冻结程序,直到我手动停止它(无论输入是否与标准匹配)。

 currentRoundAnswer = input("A sound has been played to you. What do you think is the corresponding musical note? Possible answers: C, D, E, F, G, A, H. Be sure to capitalize the letters.")

while currentRoundAnswer == "C" or "D" or "E" or "F" or "G" or "A" or "H":
    continue
else:
    playsound(currentPath)
    currentRoundAnswer = input("Sorry, you submitted your answer in an incorrect format. The sound has been played again. What do you think is the corresponding musical note? Possible answers: C, D, E, F, G, A, H. Be sure to capitalize the letters.")

更新 - 调整了 while 循环:

while currentRoundAnswer not in ["C", "D", "E", "F", "G", "A", "H"]:
    playsound(currentPath)
    currentRoundAnswer = input("Sorry, you submitted your answer in an incorrect format. The sound has been played again. What do you think is the corresponding musical note? Possible answers: C, D, E, F, G, A, H. Be sure to capitalize the letters.")
    if currentRoundAnswer not in ["C", "D", "E", "F", "G", "A", "H"]:
        continue
    else:
        break

您可以将in关键字用作:

while currentRoundAnswer in ["C", "D", "E", ...]:

while 循环是无限的,因此您的程序将在紧密循环中执行,并且可能会变得无响应。

这是因为条件不是你想象的那样,即测试用户是否输入了任何有效的注释。 它实际上是这样的:

while (currentRoundAnswer == "C") or ("D") or ("E") or ("F") or ("G") or ("A") or ("H"):
    continue

这将始终为“真”,因为即使答案不是C ,出于该条件的目的, D也被视为真。

更好的方法是使用in来测试列表或可能响应字符串的成员资格:

NOTES = 'CDEFGAH'    # where is B?
while currentRoundAnswer in NOTES:
   ...

您的代码还有很多其他问题。 逻辑无处不在,你需要看看如何在 Python 中执行用户交互。 检查此问题以获取提示询问用户输入直到他们给出有效响应

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM