-2

In my case i have to get N no. of inputs from user as per they entered. i mean,

Please enter size of an array:

and if the user enter 3 or whatever as he like, then the program should take 3 inputs from the user in a single line like

1 2 3

and also if he enters greater than 3 or what he enters the program should warn him about the input he given.

is there any way to do????

my inputs are:

Enter size of an array : 5

my outputs should be like this:

1 2 3 4 5

and the main thing is that.......... it should not ask user each and every time to enter 5 input and also it should check that the user entered correct no. of inputs.

PS: please dont mark this as "Duplicate". I searched a lot and found no answer. that's why asking here.

nasr18
  • 75
  • 1
  • 3
  • 13
  • 1
    __yes there are many ways to do this__ most of those ways will involve the following `str.split`,`input`(or `raw_input`), `int`(or `float`), at least one `for loop` and some other stuff – Joran Beasley Jun 11 '15 at 16:41
  • http://stackoverflow.com/questions/18332801/how-to-read-an-array-of-integers-from-single-line-of-input-in-python3 – Rakholiya Jenish Jun 11 '15 at 16:43
  • Also https://stackoverflow.com/questions/4663306/how-can-i-get-a-list-as-input-from-the-user-in-python – Cory Kramer Jun 11 '15 at 16:45

1 Answers1

6

You can accept their input and convert it to an int

>>> size = int(input('Enter size of array: '))
Enter size of array: 3

Then use this value within the range function to iterate that many times. Doing so in a list comprehension you can repeatedly ask for input the same way.

>>> values = [int(input('Enter a value: ')) for _ in range(size)]
Enter a value: 3
Enter a value: 5
Enter a value: 7

>>> values
[3, 5, 7]

To do this in a more step-by-step manner you can use a for loop

values = []
for _ in range(size):
    values.append(int(input('Enter a value: ')))

If you just want them to enter a line of values, don't worry about asking how many there will be. You can use split() to tokenize the string on whitespace (or whatever delimiter you pass in), then convert each value to an int.

>>> values = [int(i) for i in input('Enter some values: ').split()]
Enter some values: 3 5 7 8
>>> values
[3, 5, 7, 8]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218