-2

In my case I have to get n inputs from user as they entered

Please enter size of an array:

If the user enters 3 or whatever he likes, then the program should take 3 inputs from the user in a single line like this

1 2 3

And if he enters a value greater than 3, the program should warn him about the input he has given.

Is there any way to do this?

Input:

Enter size of an array: 5

Output:

1 2 3 4 5

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

3

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

except he wants my_input.split()[:size] I think ... but yeah
@CoryKramer if the user enter 5 as size of an array means it should not ask the user to enter 5 values again and again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.