简体   繁体   中英

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 new bee to python is there any way to find last input from stdin console???

函数输入的末尾是\\ n,因此在函数iter中仅将空字符串用作分隔符。

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 (ie, 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 an 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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM