2

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?

4

4 回答 4

6

input()在 Python 3 中返回一个字符串;您需要将输入值转换为整数,int()然后才能添加它们:

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

(当用户不输入整数时,您可能希望将其包装在try:/中以获得更好的响应。except ValueError:

于 2013-04-17T15:21:13.663 回答
4

代替(a+b), 使用(int(a) + int(b))

于 2013-04-17T15:21:52.260 回答
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")
于 2013-04-17T15:27:26.177 回答
1

默认情况下,python 将输入作为字符串。因此,您的代码中不会同时添加两个数字字符串连接。因此,您应该使用 int() 方法将其显式转换为整数。这是一个示例代码

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

有关更多信息,请查看此链接 https://codingwithwakil.blogspot.com/2021/05/python-program-to-add-two-numbers-by.html

于 2021-07-02T07:52:45.877 回答