当输入无效时,如何停止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放在循环之外。我也不能使用函数:(

您可以让for循环表现得像while循环,让它永远运行,并将i实现为计数器。然后,只有当循环达到3(或2,这样索引就不会改变(时,循环才能终止,否则它会被设置回0:

cnt_i = -1
for _ in iter(int, 1):
cnt_i += 1
if ...
else:
cnt_i = 0
if cnt_i == 2:
break

但说真的,不管不使用while循环的原因是什么,你无论如何都应该使用它。。

试试这样的方法。您可以跟踪有效输入的数量,并且只有在达到目标数量时才停止循环(while(。

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

如果你真的不能使用while循环。。。

def get_valid_input():
user_input = input(...)
valid = True
if (...):  # Do your validation here
valid = False
if valid:
return user_input
else:
return get_valid_input()
for i in range (0, 3): 
input = get_valid_input()
# Do what you need to do, basically your program from the question
...
...

这里还有一些额外的gotchas,如中所示,如果输入值不正确,您需要担心达到最大递归限制的可能性,但理想情况下,get_valid_input应该只在您确定有有效的内容时返回。

您可以将输入语句放入包含try块的while循环中。

for j in range(3): # or any other range
try:
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)?: "))
break
except:
pass

最新更新