so here is the question. I have 'for in range' for me to input value to the list however, if I input value which is not numbers, it could only tells me I enter the wrong input but I can't re-enter the right value, it just keeps asking me to move forward to enter the next one.
How could I redo the input if I entered the wrong value(ex:english characters)so I could have a right value in certain position?
Thanks a lot for any help ! rookie for python
the code I wrote is:
count=15
student=list()
print('please insert student score:')
for item in range(count):
line = input('enter score for student:'+str(item+1))
if line.isdecimal() and 0<=int(line)<=100:
data=int(line)
student.append(data)
else:
print(f"what you entered:Num{item+1:3d}is not a score")
total=0
for line in student:
total += line
totalF = total/15
print('Student Average Score is:','%.2f' % totalF)
print('Finish Input\n')
print("student:",student)
print('You have', end='--> ')
for item in student:
print(f'{item:d}', end=' ')
Extract the part of code getting the score into it's own function, and in this function put it in a while loop that will keep on asking for value until the value is valid:
def get_score(num):
while True:
value = input(f'enter score for student {num}:')
try:
# int(value) will raise a ValueError if value
# is not a proper representation of an int
value = int(value)
# now we have an int, test it's value,
# and raise a ValueError if it doesn't match
if not 0 <= value <= 100:
raise ValueError("value should be between 0 and 100")
# value is ok, done
return value
except ValueError as e:
# either it's not an int or it's not in the right range
print(f"Invalid value '{value}': {e}")
# naming tip: use a plural for collections
students = []
# tip: avoid those useless "item+1" things ;-)
for num in range(1, count+1):
score = get_score(num)
students.append(score)
You have to do your check in a loop and finish it when the score is correct.
Here with a simple boolean variable:
for item in range(count):
correct_score = False
while not correct_score:
line = input('enter score for student:'+str(item+1))
if line.isdecimal() and 0<=int(line)<=100:
data=int(line)
student.append(data)
correct_score = True # to get out of the loop
else:
print(f"what you entered:Num{item+1:3d}is not a score")
# we don't change `correct_score` here, so the loop will be executed again
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.