python - 陷入嵌套的 While 循环
问题描述
下面是我的程序的代码。我试图让这个询问用户是否要输入一组测试分数。如果是,则程序运行,获取测试分数,当用户键入结束时,循环结束,将分数相加,然后给出平均值。然后它应该询问用户是否要添加另一组测试分数。如果是,它会再次运行。如果没有,它会停止并有一个结束语句。
我在主 while 循环中有第二个 while 循环。当我运行代码时,它甚至不运行主 while 循环。以下是我对问题回答 y(是)时显示的内容。
Enter test scores
Enter end to end input
======================
Get entries for another set of scores? y
Enter your information below
Get entries for another set of scores?
它不运行原始的while循环;它让用户输入分数,完成后点击“结束”,计算分数,给出平均值,最后询问用户是否要输入另一组测试分数。
有什么建议么?我有完整的代码,就像我在下面的 PyCharm 中一样。
print("The Test Scores application")
print()
print("Enter test scores")
print("Enter end to end input")
print("======================")
# initialize variables
counter = 0
score_total = 0
test_score = 0
get_entries = 'y'
while test_score != 999:
while True:
get_entries = input("Get entries for another set of scores? ")
if get_entries == 'y':
print("Enter your information below")
else:
print("Thank you for using the Test Scores application. Goodbye!")
test_score = input("Enter test score: ")
if test_score == 'end':
break
elif (int(test_score) >= 0) and (int(test_score) <= 100):
score_total += int(test_score)
counter += 1
elif test_score == 999:
break
else:
print("Test score must be from 0 through 100. Score discarded. Try again.")
# calculate average score
average_score = round(score_total / counter)
# format and display the result
print("======================")
print("Total Score:", score_total,
"\nAverage Score:", average_score)
解决方案
您的内部循环缩进太远。while True:
前面有 5 个空格,而其他所有内容都缩进 4 个空格。此外,当我们谈论缩进时,您也有一个break
不正确的缩进。
要解决这个问题:
- 从之前删除一个空格
while True:
- 在前面加三个空格
break
- 对于加分,还要从嵌套内的 5 行中的每一行之前删除一个空格,
while
以便它们缩进 8 或 12 个空格。
提示更新的问题:
看看你的内部循环的实现。在什么情况下程序会退出该循环继续执行test_score = ...
?
推荐阅读
- javascript - PHP cURL 不发送帖子数据
- css - 完整的日历打印背景颜色?
- amazon-web-services - 使用带死信和 Lambda 的 SQS 时,为什么在 lambda 失败并出现运行时异常后消息仍“处于飞行中”状态 5 分钟?
- node.js - 使用 Spotify 授权端点时的 CSRF 保护
- ansible - 单个文件中的 Ansible 事实
- python - TypeError:'str'对象不可调用错误当我不使用任何字符串时,只有整数
- python - Instabot:是否可以在单个帖子中上传多张图片?
- javascript - 如何从后端(快递)在nodeJS中创建html文件并将其发送到客户端?
- c# - 如何在winforms c#中生成打印预览
- r - 为什么 as.formula('x') 会导致堆栈使用错误?