Entering n elements in a single line

Here is the program:

i = 1
k = 0
p = 0
n = int(input())
for i in range(1, n+1):
  a = int(input())
  if a % 2 == 0:
    k += 1
  if a % 2 != 0:
    p += 1
print(abs(k-p))

Elements can be entered into the terminal only in this way:

3
1
2
3

And you need it like this:

3
1 2 3 

How do I do this?

Author: insolor, 2019-01-20

3 answers

You can split a string into numbers:

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

Explanation: input() contains the entered string, .split() splits it on whitespace, generate a list of obtained values, then each element of the list becomes int and is added to the list of i

This expression is similar to the following:

i = []
for a in input().split():
    i.append( int(a) )

Result:

 IN: "12 214  5 24 5"
 OUT: [12, 214, 5, 24, 5]

Usage in your program:

i = 1
k = 0
p = 0
n = int(input()) # не будет использоваться
nums = [int(a) for a in input().split()]
for a in nums:
  if a % 2 == 0:
    k += 1
  if a % 2 != 0:
    p += 1
print(abs(k-p))
 5
Author: XxX, 2019-01-20 16:12:49
input1 = list(map(int, '12 214 5 24 5'.split()))
input2 = [int(a) for a in '11 213 4 23 5'.split()]

print(input1)  # [12, 214, 5, 24, 5]
print(*input2)  # 11 213 4 23 5

from itertools import chain
print(*chain(input1, input2))  # 12 214 5 24 5 11 213 4 23 5
 0
Author: vadim vaduxa, 2019-07-23 12:40:32

I suggest this option

n=int(input())

a=map(int, input().split(maxsplit=n))

print(sum(a))
 0
Author: Yuriy Semerich, 2019-09-17 06:44:10