下面的 Python 代码有一个奇怪的行为,我无法弄清楚。
程序调用 testQuery,它要求用户回答“是”以调用 scoreAverager,或“否”以退出程序。如果调用 scoreAverager,它会要求用户输入一系列分数,或“x”来完成,这会将用户返回到 testQuery,在那里他们可以选择对另一个测试进行平均或退出。
如果用户对几次测试(例如 2 次或更多)的结果进行平均,就会发生奇怪的事情。那时,对 testQuery 给出“否”将无法终止程序。它将为每个平均测试迭代一个额外的循环。我不明白为什么会这样。它看起来和行为都像一个错误的错误,但关闭循环的条件似乎已经满足。它可以通过“休息”来解决,但我宁愿知道更有机地解决它的问题是什么。
谁能让我知道为什么会发生这种奇怪的行为?
代码:
def scoreAverager():
done=0
scoreTot=0
numScores=0
average=0
while done == 0:
score=input("Enter the numerical score, or enter 'x' to finish entering scores:")
acceptedXs={"X","x"}
if score in acceptedXs:
print ("The average of the scores is: ",average)
#break #this break is necessary for proper function.
done=1
testQuery()
else:
try:
score=float(score)
scoreTot=scoreTot+score
numScores=numScores+1
average=scoreTot/numScores
except ValueError:
print("EXCEPTION: The entry was invalid, please try again.")
def testQuery():
done=0
while done == 0:
moreTests=input("Do you have a set of score to average? Enter 'Yes' or 'No':")
acceptedNos=("No","NO","no")
acceptedYess=("Yes","YES","yes")
if moreTests in acceptedNos:
print("Program Complete.")
done=1
elif moreTests in acceptedYess:
scoreAverager()
else:
print ("ERROR: The entry was invalid. Please try again.")
def main():
testQuery()
main()
输入/输出示例:
Do you have a set of score to average? Enter 'Yes' or 'No':Yes
Enter the numerical score, or enter 'x' to finish entering scores:1
Enter the numerical score, or enter 'x' to finish entering scores:2
Enter the numerical score, or enter 'x' to finish entering scores:x
The average of the scores is: 1.5
Do you have a set of score to average? Enter 'Yes' or 'No':Yes
Enter the numerical score, or enter 'x' to finish entering scores:1
Enter the numerical score, or enter 'x' to finish entering scores:2
Enter the numerical score, or enter 'x' to finish entering scores:x
The average of the scores is: 1.5
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.