Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take specific number of input in python

Tags:

python-2.7

How do I take a specific number of input in python. Say, if I only want to insert 5 elements in a list then how can I do that? I tried to do it but couldn't figure out how.

In the first line I want to take an integer which will be the size of the list. Second line will consist 5 elements separated by a space like this:

5

1 2 3 4 5

Thanks in advance.

like image 762
Varun Sharma Avatar asked Oct 19 '25 15:10

Varun Sharma


1 Answers

count = int(raw_input("Number of elements:"))
data = raw_input("Data: ")
result = data.split(sep=" ", maxsplit=count)
if len(result) < count:
    print("Too few elements")

You can also wrap int(input("Number of elements:")) in try/except to ensure that first input is actually int.

p.s. here is helpful q/a how to loop until correct input.

like image 74
Sergey Belash Avatar answered Oct 22 '25 07:10

Sergey Belash