Search code examples
pythoninputsplitlimitraiserror

getting limited inputs in python


As you can see the user has entered more than 3 numbers for the age-input and it is not correct to be like this. What I want is to get limited numbers in my inputs, I mean if the quantity of students are 3 so how can I return an error if the user write more than 3 for it's height/weight/age ?

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']]

Solution

  • Here is how:

    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)
    



    If you wish to ignore the extra values, and only append the wanted amount, here is a method similar to Sanket's, only we will be making use of the second parameter of the str.split() method to optimize the efficiency:

    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)
    

    You see, if we don't add the second parameter, if the user input many values, the program will first split all the values, even when we, like, only need the first 3.