I want to know how to handle multi lines input on python 3.
When the input is
10
1
6
8
5
4
7
3
2
9
0
, and the code is
numbers=[]
n = int(input()) # Get n numbers
for i in range(n): # Add n numbers in list
numbers.append(int(input()))
I cannot input the text by copy & paste whole text block, cause python console gave me ValueError. I have to type line by line using Enter Key on keyboard.
My solution looks like below.
sample_input=input().splitlines()
n = int(sample_input[0]) # Get n numbers
data=[]
for i in range(1, n 1): # Add n numbers in list
data.append(int(sample_input[i]))
But I think this is messy code. What can be a better way for this one?
CodePudding user response:
One solution:
sample_input=input().splitlines()
sample_input_as_int = [int(value) for value in sample_input]
n, *data = sample_input_as_int
if len(data) != n:
raise ValueError("wrong number of data provided")
Do you really need to ask the user how many numbers they are going to enter? If they enter only the numbers, you can simplify the code:
sample_input=input().splitlines()
data = [int(value) for value in sample_input]