python - 当输入无效时,如何停止 for 循环迭代?(不允许使用 while 循环)- Python
问题描述
for i in range (0, 3):
print() # When iterates creates a space from last section
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
penalty = (days_late * 5)
final_mark = (raw_mark - penalty)
# Selection for validation
if 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark >= 40:
print("Student ID:", str(student_id[i]))
print() # Spacing for user readability
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("This means that the result is now:", final_mark,"(this was not a capped mark)")
elif 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark < 40: # Final mark was below 40 so mark must be capped
print("Student ID:", str(student_id[i]))
print()
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("Therefore, as your final mark has dipped below 40, we have capped your grade at 40 marks.")
else:
print("Error, please try again with applicable values")
在其他情况下,我希望循环循环返回,但没有将 i 迭代到下一个值,因此它可以是无限的,直到输入所有 3 个有效输入......不能使用 while 循环,我也不能放 if - elif- else 在循环之外。我也不能使用函数:(
解决方案
尝试这样的事情。您可以跟踪有效输入的数量,并且只有在while
达到目标数量后才停止循环(the )。
valid_inputs = 0
while valid_inputs <= 3:
...
if ...:
...
elif ...:
...
else:
# Immediately reset to the top of the while loop
# Does not increment valid_inputs
continue
valid_inputs += 1
推荐阅读
- python - np.subtract() - ValueError 用 numpy 减去列表
- android - 无法获取外部文件目录。外部存储状态在 Android 上挂载
- kubernetes - Kubernetes 不允许删除部署 - 服务器找不到请求的资源
- angular - 来自 API 的数据未显示在 Angular html 模板中
- windows - 匹配两个列表并使用 Powershell 查找卸载字符串
- reactjs - 使用单个 onChange 反应钩子处理多个文本字段
- flutter - 如何解决颤振中的 gradle 错误?
- javascript - 仅在用户使用角度、打字稿确认时切换开关
- python - 变量输出导致意外结果
- angular - Angular Universal ssr - 静态预渲染