Search code examples
pythonpython-2.7raw-input

How to insert as many numbers as were mentioned before using raw_input?


I want the user of my program to provide a number and then the user must input that number of numbers.

My input collection code

inp1 = int(raw_input("Insert number: ")) 
inp2 = raw_input("Insert your numbers: ")

Example:

If the user enters 3 at Insert number: then they have to input three numbers (with spaces between them) at Insert your numbers:.

How do I limit the number of values in the second response to the amount specified in the first response?


I assume, we should use a list to work with.

my_list = inp2.split()

I'm using Python 2.7


Solution

  • Use the len function to get the length of the list, then test if it is correct:

    inp1 = int(raw_input("Insert number: "))
    inp2 = raw_input("Insert your numbers: ").split()
    while len(inp2) != inp1:
        print "Invalid input"
        inp2 = raw_input("Insert your numbers: ").split()
    

    Another approach would be to get each input on a new line seperately, with a loop:

    inp1 = int(raw_input("Insert number: "))
    inp2 = []
    for i in range(inp1):
        inp2.append(raw_input("Enter input " + str(i) + ": "))
    

    This way, there are no invalid inputs; the user has to enter the right amount of numbers. However, it isn't exactly what your question asked.