Python与从STDIN读取的C++代码等价?

2024-09-27 19:18:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我加入了黑暗面并决定学习Python。我使用的是python3。在

这是一个直接向前的方法,用C++一次读取两个整数,直到它们都是0:

int x, y;
while (cin >> x >> y && (x != 0 || y != 0)) {
    //x or y can be 0 but not both
}
//now x = 0 and y = 0 OR can't find two int's

它简单易行,99.999%的时间都能用。我在Python中有以下内容,但对我来说它似乎不是Python。此外,这在某些输入上注定会失败(例如,如果int在两个不同的行上)

^{pr2}$

有人能告诉我使用python3一次读取两个int直到两个int都为0的最干净的Python方法吗?在


Tags: orand方法not整数becannow
3条回答

对于python2.x,您将希望使用^{},而对于python3.x,您只需使用^{}

inputs = raw_input("Enter two numbers")
values = [int(x) for x in inputs.split()]

示例代码几乎是合理的,只是它可以立即解包变量并使用异常处理来处理错误

import sys

while True:
    try:
        x,y = [int(i) for i in sys.stdin.readline().split()]
        if x == 0 and y == 0:
            break
        print(x+y)
    except ValueError:
        # didn't have 2 values or one of them isn't an int
        break
print("both are 0 or couldn't find 2 int's")

试试这个。我的简单测试似乎有效。但是,如果您只键入一个数字,它将抛出一个错误。在

while True:
    x,y = map(int, input().split())
    if x == 0 and y == 0:
        break
    print(x + y)
print("both are 0 or couldn't find 2 int's")

这个版本正确地处理了“找不到2个整数”的情况。在

^{pr2}$

相关问题 更多 >

    热门问题