【问题标题】:getting limited inputs in python在 python 中获得有限的输入
【发布时间】:2020-06-28 18:05:23
【问题描述】:

如您所见,用户为年龄输入输入了 3 个以上的数字,这样是不正确的。 我想要的是在我的输入中获得有限的数字,我的意思是如果学生的数量是 3,那么如果用户的身高/体重/年龄超过 3,我该如何返回错误?

classAcounter=int(input("How many students? "))
classAlist=[]

height=input().split(" ")
weight=input().split(" ")
age=input().split(" ")

classAlist.append(height)
classAlist.append(weight)
classAlist.append(age)

print(classAlist)

#input:
3
175 170 183 188
70 68 83
18 19 18 19

output:
[['175', '170', '183', '188'], ['70', '68', '83'], ['18', '19', '18']]

【问题讨论】:

  • 您需要进行布尔测试。查看 if 语句。

标签: python input split limit raiserror


【解决方案1】:

方法如下:

classAcounter=int(input("How many students? "))
classAlist=[]

height = input().split(" ")
weight = input().split(" ")
age = input().split(" ")

if len(height)==len(weight)==len(age)==classAcounter:
    classAlist.append(height)
    classAlist.append(weight)
    classAlist.append(age)
else:
    print('Error: Inconsistent amount of info')

print(classAlist)



如果你想忽略多余的值,只附加想要的数量,这里有一个类似于 Sanket 的方法,只是我们将利用 str.split() 方法的第二个参数来优化效率:

classAcounter=int(input("How many students? "))
classAlist=[]

height = input().split(" ",classAcounter)[:classAcounter]
weight = input().split(" ",classAcounter)[:classAcounter]
age = input().split(" ",classAcounter)[:classAcounter]

classAlist.append(height)
classAlist.append(weight)
classAlist.append(age)

print(classAlist)

你看,如果我们不添加第二个参数,如果用户输入了很多值,程序会先拆分所有个值,即使我们只需要前3个.

【讨论】:

    【解决方案2】:

    您可以执行以下操作:

    classAcounter=int(input("How many students? "))
    classAlist=[]
    
    height=input().split(" ")[:classAcounter]
    weight=input().split(" ")[:classAcounter]
    age=input().split(" ")[:classAcounter]
    
    classAlist.append(height)
    classAlist.append(weight)
    classAlist.append(age)
    
    print(classAlist)
    

    #input:

    3
    175 170 183 188
    70 68 83
    18 19 18 19
    

    输出:

    [['175', '170', '183'], ['70', '68', '83'], ['18', '19', '18']]
    

    但是,这不能限制用户使用 eterig 多个值,但这会限制您使用用户输入的所有值。

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 1970-01-01
      • 2021-04-16
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多