Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read only two numbers from python STDIN Function?

I want to take two numbers through the stdin python function and output their total.

import sys

num1 = None
num2 = None

print('Please Enter Two Numbers to Find their Sum or Enter q to quit')
for line in sys.stdin:
    if('q'==line.strip()):
        break
    else:
        num = int(line.strip())
        if(num1 == None):
            num1 = num
        elif(num2 == None):
            num2 = num
        else:
            break

total = num1 + num2
print(total)

I want the code to do the following:

Please Enter Two Numbers to Find their Sum or Enter q to quit    
12
11
23

When I run the above code it takes 3 numbers and then gives me the total of the first two numbers.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please Enter Two Numbers to Find their Sum or Enter q to quit
12
11
13
23

I only want it to take 2 numbers and output their total. What do I need to change in the code to do so?

>Solution :

The issue is that your code continues to read input until it encounters a ‘q’ or until it has read three numbers. To fix this, you can modify the code to break out of the loop as soon as it has read two numbers. Here’s the modified code:

import sys

num1 = None
num2 = None

print('Please Enter Two Numbers to Find their Sum or Enter q to quit')
for line in sys.stdin:
    if('q'==line.strip()):
        break
    else:
        num = int(line.strip())
        if(num1 == None):
            num1 = num
        elif(num2 == None):
            num2 = num
            break  # Break out of the loop after reading the second number

if num1 is not None and num2 is not None:
    total = num1 + num2
    print(total)
else:
    print("You didn't enter two numbers.")

In this modified code, the loop will break as soon as it has read two numbers, and then it will calculate and print their sum. If the user enters ‘q’ before entering two numbers, it will print a message indicating that they didn’t enter two numbers.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading