Python while循环内部的for循环不断重复,而value无效

时间:2017-04-01 00:25:57

标签: python loops for-loop while-loop repeat

这是我的代码:

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

我的问题是如何检查等级是否在范围内,并在输入错误输入时重复循环。当我尝试运行程序并输入超量程输入时,它将转到下一个评估编号,而不是再次尝试,直到它成立为止。

1 个答案:

答案 0 :(得分:0)

你可以使用这样的东西,它使用while True循环和try statement and except clause来确定用户是否输入了有效等级:

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

使用示例:

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:
...

试试here!