DRV
DRV

Reputation: 756

Read multiple inputs from multiple line in python

Input:
691 41
947 779

Output:
1300
336

I have tried this solution a link

but my problem is end of last line is unknown

My Code:

for line in iter(input,"\n"):                                                               
    a,b = line.split()
    a = int(a)
    b = int(b)
    result = 2 * (a - b)
    print(result)

My code is printing the desired output but the for loop is not terminating. I am a new bee to python is there any way to find the last input from the stdin console???

Upvotes: 0

Views: 789

Answers (4)

gboffi
gboffi

Reputation: 25100

What are you missing is that input() strips the newline from the end of the string it returns, so that when you hit <RET> all alone on a line what iter() sees (i.e., what it tests to eventually terminate the loop) is not "\n" but rather the empty string "" (NB definitely no spaces between the double quotes).

Here I cut&paste an example session that shows you how to define the correct sentinel string (the null string)

In [7]: for line in iter(input, ""):
   ...:     print(line)
   ...:     
asde
asde


In [8]: 

As you can see, when I press <RET> all alone on a n input line, the loop is terminated.

ps: I have seen that gcx11 has posted an equivalent answer (that I've upvoted). I hope that my answer adds a bit of context and shows how it's effectively the right answer.

Upvotes: 2

Kruup&#246;s
Kruup&#246;s

Reputation: 5484

Probably not what you need, but I didn't figure out where your inputs comes from, I tried to adapt your code by reading everything from std in using fileinput and leaving when "Enter" is pressed:

import fileinput

for line in fileinput.input():
    if line == '\n':
        break
    a, b = line.split()
    a = int(a)
    b = int(b)
    result = 2 * (a - b)
    print(result)

Upvotes: 0

Edwin van Mierlo
Edwin van Mierlo

Reputation: 2488

you mentioned that you tried this But it seems that you implement a '\n' as sentinel (to use a term from the post from the link).

You may need to try to actually use a stop word, something like this:

stopword = 'stop'
for line in iter(input, stopword):                                                               
    a,b = line.split()
    a = int(a)
    b = int(b)
    result = 2 * (a - b)
    print(result)

Upvotes: 0

gcx11
gcx11

Reputation: 128

Function input is stripping trailing \n, so just use empty string as delimiter in function iter.

Upvotes: 2

Related Questions