I was just getting into Python programming. I wrote a simple program to calculate sum of two user-input numbers:
JavaScript
x
3
1
a,b = input("enter first number"), input("enter second number")
2
print("sum of given numbers is ", (a+b))
3
Now if I enter the numbers as 23 and 52, what showed in the output is:
JavaScript
1
2
1
sum of given numbers is 23 52
2
What is wrong with my code?
Advertisement
Answer
input()
in Python 3 returns a string; you need to convert the input values to integers with int()
before you can add them:
JavaScript
1
2
1
a,b = int(input("enter first number")), int(input("enter second number"))
2
(You may want to wrap this in a try:
/except ValueError:
for nicer response when the user doesn’t enter an integer.