0

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
asked Dec 7, 2017 at 20:39
4
  • What integer is 1 4 supposed to be? Commented Dec 7, 2017 at 20:40
  • This is not a single integer, it's a input consisting of two integers 1 & 4 and we have to deal with them separately and add 4 to list Commented Dec 7, 2017 at 20:41
  • Or in other words, why is the second input 1 4 if you want it to be a second integer. Commented Dec 7, 2017 at 20:41
  • Also, if you use Python 2, use raw_input(), because plain input() interprets the string; try typing exit() and see what happens. Commented Dec 7, 2017 at 20:45

2 Answers 2

3

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

Comments

1

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.