Search code examples
python-3.xstdoutstdin

How to take inputs and display their sum using stdin and stdout


I wrote a simple code to add two numbers with stdin and stdout to take input and display output respectively:

import sys
print("Inputs:")
for one in sys.stdin:
    break
int(one)

for two in sys.stdin:
    break
int(two)

three = 0

print("Output:")
three = one + two

sys.stdout.write(three)

The output i get is:

Inputs:
1
2
Output:
1
2

The expected output was 3. But what I got is show in above output.

I tried the same code using input():

one = int(input())

two = int(input())

three = one + two

print(three)

And the output I got was 3. What is missing in my first code?


Solution

  • I think what you're trying to do is:

    aNumber = input('Enter a number: ')
    anotherNumber = input('Enter another number: ')
    print(int(aNumber) + int(anotherNumber))
    

    To do this using stdin/out you can use:

    import sys
    print("Inputs:")
    one = sys.stdin.readline()
    two = sys.stdin.readline()
    print("Output:")
    three = int(one) + int(two)
    four = str(three)
    sys.stdout.write(four)