Rob L
Rob L

Reputation: 3303

What is the Python equivalent to this C++ code that reads from stdin?

I have joined the dark side and have decided to learn Python. I am using Python 3.

Here is a straight forward way using C++ to read two integers at a time until both of them are 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

It's easy, simple and works 99.999% of the time. I have the following in Python but it doesn't seem Pythonic to me. Also, this is doomed to fail on some inputs (i.e. if the int's are on 2 different lines)

while True:
        line = sys.stdin.readline()
        values = [int(i) for i in line.split()]
        if (values[0] == 0 and values[1] == 0):
            break
        x = values[0]
        y = values[1]
        print(x + y)
print("both are 0 or couldn't find 2 int's")

Can someone please tell me the cleanest, most Pythonic way to read two int's at a time until both are 0 using Python 3?

Upvotes: 2

Views: 342

Answers (4)

tdelaney
tdelaney

Reputation: 77347

The example code is almost reasonable except that it could unpack the variables immediately and use exception handling to deal with errors

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")

Upvotes: 1

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

More generally, you can apply a typelist to a sequence of whitespace-separated values:

>>> types = (int, str, int, float)
>>> inputs = '1234 "WESTA" 4 1.05'
>>> values = inputs.split()
>>> (type(value) for (type, value) in zip(types, values)
(1234, 'WESTA', 4, 1.05)

You could also trust the interpreter to create the correct type with ast.literal_eval

>>> map(literal_eval, values)
[1234, 'WESTA', 4, 1.05]

Upvotes: 0

Suever
Suever

Reputation: 65430

With Python 2.x you'll want to use raw_input whereas for Python 3.x you use simply input

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

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191738

Try this out. My simple tests seem to work. It will throw an error if you only type one number, though.

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")

This version correctly handles the "couldn't find 2 int's" case.

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

Upvotes: 1

Related Questions