python - 如何使用 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
解决方案
在将这些值传递给字典之前,您可以阻止任何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))
推荐阅读
- python - AWS 上的 Flask 无法识别控制器
- reactjs - 任何推荐的方法来按预定义的顺序顺序执行 Jest 测试?
- embedded-linux - 组织 Yocto 项目存储库(-ies)的推荐方法是什么?
- javascript - if - else if 具有假值的语句
- android - 构建 APK - 片段 buildConfig.class 错误
- centos - 邮件 -r 选项被忽略
- javascript - React Native - 如何水平滑动卡片并给它们留出边距
- amazon-web-services - 如何在本地服务器上配置 AWS 角色?
- r - 比较两个数据框中的名称
- elasticsearch - Logstash 无法识别的国家/地区 VM 选项“UseParNewGC”