3

I was just getting into Python programming. I wrote a simple program to calculate sum of two user-input numbers:

a,b = input("enter first number"), input("enter second number")
print("sum of given numbers is ", (a+b))

Now if I enter the numbers as 23 and 52, what showed in the output is:

sum of given numbers is  23 52

What is wrong with my code?

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
R4M
  • 73
  • 1
  • 6

4 Answers4

6

input() in Python 3 returns a string; you need to convert the input values to integers with int() before you can add them:

a,b = int(input("enter first number")), int(input("enter second number"))

(You may want to wrap this in a try:/except ValueError: for nicer response when the user doesn't enter an integer.

Wooble
  • 87,717
  • 12
  • 108
  • 131
  • This worked too, but I feel this a bit difficult... But thanks for introducing me to this method... :) <3 – R4M Apr 17 '13 at 15:54
4

instead of (a+b), use (int(a) + int(b))

mcvz
  • 494
  • 4
  • 13
  • Thanks!! This was easier than adding datatype while initializing itself (for me)... :) A thousan thanks!!! <3 – R4M Apr 17 '13 at 15:53
  • 1
    My Pleasure :) This has the added benefit of keeping your original strings a and b intact, which might be useful later in your program. – mcvz Apr 18 '13 at 07:38
4

I think it will be better if you use a try/except block, since you're trying to convert strings to integers

try:
    a,b = int(input("enter first number")), int(input("enter second number"))
    print("sum of given numbers is ", (a+b))
except ValueError as err:
    print("You did not enter numbers")
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Fernando Freitas Alves
  • 3,709
  • 3
  • 26
  • 45
1

By default python takes the input as string. So instead of adding both the numbers string concatenation is occurring in your code. So you should explicitly convert it into integer using the int() method. Here is a sample code

a,b=int(input("Enter the first number: ")),int(input("Enter the second number: "))
print("Sum of the numbers is ", a + b)

For more information check this link https://codingwithwakil.blogspot.com/2021/05/python-program-to-add-two-numbers-by.html