你如何在Python中将两个变量加在一起?

时间:2014-01-10 13:35:26

标签: python python-3.x addition

variable1 = 3
variable2 = "Hello"
print("variable 1 is", variable1)
print("variable 2 is", variable2)
print("Enter a new value for variable 1: ")
variable1 = input()
print("variable 1 is now ", variable1)
print("Enter a new value for variable 2: ")
variable2 = input()
print("variable 2 is now ", variable2)
variable3 = variable1+variable2
print("Variable 3 is the addition of variable 1 and 2 which is ", variable3)

运行程序时,variable1和variable2怎么没有正确加起来?谢谢你的阅读!

1 个答案:

答案 0 :(得分:3)

默认情况下,input将用户输入的数据作为字符串返回。因此,当您在两个字符串上使用+运算符时,它会将它们连接起来。您需要将它们显式转换为int,如此

variable1 = int(input())
...
variable2 = int(input())