简体   繁体   中英

Python While loop inside a for loop that keeps on repeating while value is invalid

This is my code:

for i in range(1, 5):
    try:
        grade = int(input("Please enter {}'s grade for practical assessment {}: ".format(name, i)))
        while (grade < 0 and grade > 40):
            print("That is not a valid grade.")
            continue
    except ValueError:
        print("That is not a valid value.")
        continue

My question is that how to check if the grade is in range and to make the loop repeat if a false input is entered. When I tried to run the program, and enter an over range input, it goes to the next assessment number instead of trying again until it's true.

You could use something like this which uses a while True loop as well as a try statement and except clause to determine whether the user entered a valid grade:

names = ["Adam", "Bob", "Chloe"] # Example list of names

for name in names:
  for i in range(1, 5):
    while True:
      try:
        grade = int(input("Please enter {}'s grade for practical assessment {}: ".format(name, i)))
        if not (0 <= grade <= 40):
          raise ValueError()
      except ValueError:
        print("Error: Please enter a grade between 0 and 40")
      else:
        break

Example Usage:

Please enter Adam's grade for practical assessment 1:  a
Error: Please enter a grade between 0 and 40
Please enter Adam's grade for practical assessment 1:  -1
Error: Please enter a grade between 0 and 40
Please enter Adam's grade for practical assessment 1:  10
Please enter Adam's grade for practical assessment 2:  4
Please enter Adam's grade for practical assessment 3:
...

Try it here!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM