首页 > 解决方案 > 如何使用 while 语句确保一维数组有效?

问题描述

我正在尝试检查每个整数(数组)是否有效(0 到 30 之间)。当告诉用户分数无效的行运行但变量似乎不是 False 时出现问题,我不知道为什么,有人可以解决这个问题吗?

这是有问题的代码:

while valid_score == True and program_running == True:
      for counter in range(0,6):
            print("How mant points did player", counter + 1 ,"earn?") 
            score_earned[counter] = int(input())

            if score_earned[counter] < 0 or score_earned[counter] > 30: 
                  print("That value was invalid as it was lower than 0 or `above 30!")`
                  valid_score = False

            else:
                  valid_score = True


            total_score = score_earned[counter] + total_score

      valid_score = False

标签: pythonarraysloopswhile-loop

解决方案


在将这些值传递给字典之前,您可以阻止任何points不在您想要的范围内的尝试输入。您可以使用while仅接受该范围的循环来执行此操作points

score_earned = {}  
players = 5

for i in range(1, players +1):
    points = -1
    while points < 0 or points > 30:
        try:
            points = int(input('Enter points for player {} between 0 and 30: '.format(i)))
        except ValueError:
            print('Please enter points between 0 and 30')
    score_earned[i] = points

total_score = sum(score_earned.values())
print('The total score is: {}'.format(total_score))

推荐阅读