2

I'm not very old in programming, I wanna input a number (n) and depending on it, I wanna input n integers separated with one space using while loop(e.g) I tried:

a = list(map(int, input().split()))

but I found that I can input number of integers exceed the value n

Very hopeful to help me Thanks in advance

M-Chen-3
  • 2,036
  • 5
  • 13
  • 34
Amir Tarek
  • 33
  • 4
  • If you only want the first `n` you can do `list(map(int, input().split()))[:n]` – ssp Dec 03 '20 at 21:16
  • I'm using a counter and every time I decrement it, I'm allowed to input new integer until the counter reaches zero – Amir Tarek Dec 03 '20 at 21:20

2 Answers2

0

you can do this in 2 main easy ways:

  1. accept an arbitrary input, split it an take the first n values there and/or throw an error/message if you get a different number of entries

     n = int(input("pick a number: "))
     list_number =  list(map(int, input(f"enter {n} numbers").split())) 
     if len(list_number)==n:
         print("cool")
         #do your stuff
     else:
         print("not cool")
         #do something about it
    
  2. take the numbers one at the time and repeat this n times, for that you need to specify the number of loops you want to do, which is make easy with the use of range(n) which produce a serie of number from 0 to n-1:

     >>> list(range(5))
     [0, 1, 2, 3, 4]
     >>>
    

    but what is relevant here is that we get n elements, so something like this for example:

     n = int(input("pick a number: "))
     list_number=[]
     for i in range(n): 
         list_number.append(int(input("enter a number: ")))
     #do your stuff
    

Also check this Asking the user for input until they give a valid response for a more detailed example

Copperfield
  • 8,131
  • 3
  • 23
  • 29
0

More "pythonic" than chaining list and map would be a list comprehension:

user_input = input()
a = [int(s) for s in user_input.split()]

Then take the n first elements of this list as suggested by @Moosefeather in the comments. You should wrap the whole thing in a try/except block to catch ValueErrors if anything in the input is not an integer, or IndexErrors if the given input is not long enough.

Antimon
  • 597
  • 3
  • 10