Vinit Raj
Vinit Raj

Reputation: 1910

how to get user input in same line in python whenever there is some condition?

I am new to python and one thing i was wondering to do is to take user input like this:-


    >> 4 # This is the Number of test Case
    >> 1
    >> 2 5
    >> 2 7
    >> 2 9

so on and so forth. so I tried this way:-

Q=int(input())
for i in range(Q):
    x = int(input())
    if x == 1:
       #do something  
    elif x==2:
        item=int(input()).split()

but after doing this i am not getting my desired output,it is like:-


    >>4
    >>1
    >>2
    >>5
    >>2
    >>7
    >>2
    >>9
    >>1

Please help me out i am new to python!

Upvotes: 0

Views: 282

Answers (2)

lorenzofeliz
lorenzofeliz

Reputation: 607

You need to check on the length of what you read, when reading value of x = int(input()). Read the value of x as string.

Q=int(input())
for i in range(Q):
    x = input()
    if len(x) == 1:
      print(int(x))
    elif len(x) > 1:
        item=x.split()
        print(int(item[0]))
        print(int(item[1]))

Upvotes: 1

vks
vks

Reputation: 67968

You cannot split an int.Once you change that rest of the code is working fine.

Q=int(input())
for i in range(Q):
    x = int(input())
    if x == 1:
        pass
        #do something
    elif x==2:
        print "enter string"
        item=input().split()

print item

Input:5 1 2 enter string "hello world" 3 4 5

Upvotes: 1

Related Questions