在下面的程序中,我们使用了 +
运算符来添加两个数字。
示例 1:添加两个数字
# This program adds two numbers
num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
输出
The sum of 1.5 and 6.3 is 7.8
下面的程序计算用户输入的两个数字之和。
示例 2:使用用户输入添加两个数字
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
输出
Enter first number: 1.5 Enter second number: 6.3 The sum of 1.5 and 6.3 is 7.8
在这个程序中,我们要求用户输入两个数字,然后程序会显示用户输入的两个数字之和。
我们使用内置函数 input() 来获取输入。由于 input()
返回一个 字符串,我们使用 float() 函数将字符串转换为数字。然后,将这些数字相加。
另一种方法是,我们可以在不使用任何变量的情况下,在一个语句中完成此加法,如下所示。
print('The sum is %.1f' %(float(input('Enter first number: ')) + float(input('Enter second number: '))))
输出
Enter first number: 1.5 Enter second number: 6.3 The sum of 1.5 and 6.3 is 7.8
尽管此程序不使用任何变量(内存效率高),但它更难阅读。