简体   繁体   English

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

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

I'm trying to make a while-loop that accepts specific inputs, but asks the user to resubmit if the input doesn't match the criteria.我正在尝试制作一个接受特定输入的 while 循环,但如果输入与条件不匹配,则要求用户重新提交。 However, after having added the while-loop, entering an input simply freezes the program until I manually stop it (no matter whether the input matches the critera or not).但是,在添加了 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.")

Update - the while-loop was adjusted:更新 - 调整了 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

You can use the in keyword as:您可以将in关键字用作:

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

The while loop is infinite so your program will execute in a tight loop and will probably become unresponsive. while 循环是无限的,因此您的程序将在紧密循环中执行,并且可能会变得无响应。

This is because the condition is not what you think it is, ie testing whether the user entered any of the valid notes.这是因为条件不是你想象的那样,即测试用户是否输入了任何有效的注释。 It is actually like this:它实际上是这样的:

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

which will always be "true" because even if the answer is not C , D is considered true for the purposes of the condition.这将始终为“真”,因为即使答案不是C ,出于该条件的目的, D也被视为真。

A better way would be to use in to test membership of a list or string of possible responses:更好的方法是使用in来测试列表或可能响应字符串的成员资格:

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

There are a lot of other problems with your code.您的代码还有很多其他问题。 The logic is all over the place and you need to look at how to perform user interaction in Python.逻辑无处不在,你需要看看如何在 Python 中执行用户交互。 Check this question for tips Asking the user for input until they give a valid response检查此问题以获取提示询问用户输入直到他们给出有效响应

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

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