I am trying to take input from a single line in Python but it's not working.
Error:
Traceback (most recent call last):
File "solution.py", line 4, in <module>
a = int(input())
ValueError: invalid literal for int() with base 10: '1 4'
Code:
q = int(input())
lis = []
for i in range(q) :
a = int(input())
print(a)
if(a==1) :
b = int(input())
lis.append(b)
else :
print("Do Nothing")
In this code for a given integer i.e.,q.
I have to take two inputs and if the first integer is 1 then we have to add the second input to the array.
Form input:
5
1 4
1 9
If input of first line is 1, we have to add 4 to list. I am unable to take input in line 1 as only 1 it is taking both 1 4.
Schleichardt
7,5421 gold badge29 silver badges37 bronze badges
2 Answers 2
Split the input, then convert to int, then do whatever
a = input().split()
a=[int(x) for x in a]
#a is now a list of ints
....#do other stuff
answered Dec 7, 2017 at 20:42
SuperStew
3,0742 gold badges18 silver badges29 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
This is the most basic way of doing it
string = input() # Read Input as string
print(string)
str_array = string.split(" ") # Split the string
print(str_array)
int_arr = [int(i) for i in str_array] # Parse the individual strings to int
print(int_arr)
Output
1 56 9 87 7
['1', '56', '9', '87', '7']
[1, 56, 9, 87, 7]
If you really want the most pythonic way of doing it
int_arr = [int(i) for i in input().split(" ")]
answered Dec 7, 2017 at 20:45
DollarAkshay
2,1191 gold badge21 silver badges41 bronze badges
Comments
lang-py
1 4supposed to be?1 4if you want it to be a second integer.raw_input(), because plaininput()interprets the string; try typingexit()and see what happens.