One option is to have an inner infinite loop (i.e. while True
) that you break
from when you get a valid answer. For example:
num_pass = 0
num_fail = 0
loopcount = 11
r = range(1, loopcount)
for student in r:
while True:
grade = int(input('1 for pass 2 for fail '))
if grade == 1:
num_pass = num_pass + 1
break
elif grade == 2:
num_fail = num_fail + 1
break
else:
print('please try again')
print('Passes:', num_pass)
print('Failed:', num_fail)
The else
block here is optional, but it is confusing without it, because there is no indication whether the next occurrence of the question is still asking about the same student or the next one.
You might also want to guard against non-numeric input that might otherwise cause your program to abort with an error when it tries to convert it to an int. For this, use exception handling, replace the line:
grade = int(input('1 for pass 2 for fail '))
with:
try:
grade = int(input('1 for pass 2 for fail '))
except ValueError:
print('that was not a number')
continue