简体   繁体   English

为什么它的工作方式不同,即使它在 python 尝试中几乎相同的代码除外?

[英]Why does it work differently even though it's almost the same code in python try except?

The question I want to solve is to input two numbers and output the sum until the user finishes.(until the user inputs ctrl+d) Of course, I can solve the problem using sys.stdin, but I want to solve it using while.我要解决的问题是输入两个数字和 output 的总和,直到用户完成。(直到用户输入 ctrl+d)当然,我可以使用 sys.stdin 解决问题,但我想使用 while 解决. The two codes below are my codes, the first one works well, but the second one doesn't work well.下面的两个代码是我的代码,第一个效果很好,但是第二个效果不好。 I don't know the difference between two codes.我不知道两个代码之间的区别。 If anybody knows about the reason, please explain why..如果有人知道原因,请解释原因..

from sys import stdin 
# in this code, when I input ctrl d, program is finished
    try:
        while True:
            a,b = map(int, stdin.readline().split())
            print(a+b)
    except:
        exit()

from sys import stdin 
# in this code, when I input ctrl d, 0 is printed out
    try:
        while 1:
            print(sum(map(int, stdin.readline().split())))
    except:
        exit()

readline() doesn't fail at EOF; readline()在 EOF 时不会失败; it just returns an empty string.它只返回一个空字符串。 Splitting an empty string is fine.拆分空字符串很好。 map ping int across an empty list is fine. map ping int在一个空列表上很好。 Summing an empty iterable is fine (and results in zero).对空的迭代求和是可以的(结果为零)。

In the first version, it’s the a, b unpacking that fails, but there's no way to tell the difference when you throw away all the exception information and catch an overly broad class of exceptions at the same time.在第一个版本中,a, b解包失败,但是当您丢弃所有异常信息并同时捕获过于宽泛的 class 异常时,无法区分。

Never use except ;永远不要使用except ; use except Exception to avoid catching low-level flow control exceptions.使用except Exception来避免捕获低级流控制异常。 And if you feel the need to catch an exception you will otherwise ignore, consider logging the fact that you caught it for debugging purposes.如果您觉得需要捕获一个您会忽略的异常,请考虑记录您捕获它的事实以用于调试目的。

If you want to use sys.stdin , a for loop is better ( line will continue to end with \n ):如果你想使用sys.stdin ,一个 for 循环更好( line继续以\n结尾):

for line in stdin:
    print(sum(map(int, line.split())))

If you want to use a while loop, input is better:如果你想使用while循环, input更好:

while True:
    try:
        line = input()
    except EOFError:
        break

    print(sum(map(int, line.split())))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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