Python 程序:相加两个数字
在该程序中,您将学习加两个数字并使用print()函数显示它。
要理解此示例,您应该了解以下 [Python 编程]( "Python tutorial")主题:
在下面的程序中,我们使用+运算符将两个数字相加。
示例 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: '))))
尽管此程序不使用任何变量(内存有效),但更难阅读。