1

So I am trying to teach myself python and I am having some problems accomplishing this task. I am trying to read in two integers from the keyboard, but the problem is that they can either be read in on the same line or on two different lines.

Example Inputs:

23 45

or

23
45

Each number should go to its own variable. Im pretty sure I should make use of the strip/split functions, but what else am I missing? I just really dont know how to go about this... Thanks.

Here is what Im working with, but obviously this version takes the numbers one on each line.

def main():
  num1 = int(input())
  num2 = int(input())
  numSum = num1 + num2
  numProduct = num1 * num2
  print("sum = ",numSum)
  print("product = ",numProduct)
main()
Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30

2 Answers2

2

the input terminates on new line (more percisely, the sys.stdin flushes on new line), so you get the entire line. To split it use:

inputs = input("Enter something").split() # read input and split it
print inputs

applying to your code, it would look like this:

# helper function to keep the code DRY
def get_numbers(message):
    try:
        # this is called list comprehension
        return [int(x) for x in input(message).split()]
    except:
        # input can produce errors such as casting non-ints
        print("Error while reading numbers")
        return []

def main():
     # 1: create the list - wait for at least two numbers
     nums = []
     while len(nums) < 2:
         nums.extend(get_numbers("Enter numbers please: "))
     # only keep two first numbers, this is called slicing
     nums = nums[:2]
     # summarize using the built-in standard 'sum' function
     numSum = sum(nums)
     numProduct = nums[0] * nums[1]
     print("sum = ",numSum)
     print("product = ",numProduct)

main()

Notes on what's used here:

You can use list comprehension to construct lists from iterable objects.

You can use sum from the standard library functions to summarize lists.

You can slice lists if you only want a part of the list.

Community
  • 1
  • 1
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
0

Here I have modified your code.

def main(): num1 = int(input("Enter first number : ")) num2 = int(input("\nEnter second number : ")) if(num1<=0 or num2<=0): print("Enter valid number") else: numSum = num1 + num2 numProduct = num1 * num2 print("sum of the given numbers is = ",numSum) print("product of the given numbers is = ",numProduct) main()

If you enter invalid number it prints message Enter valid number.

iamjayp
  • 386
  • 4
  • 16
  • You asked for using input instead of raw_input. So answer is you can use only input instead of raw_input. Because raw_input is used to enter the string value and input is for entering only the integer values. – iamjayp Feb 06 '15 at 06:35