Python Sum of Numbers
The following example takes two numbers from the user and computes their sum:
Example (Python 3.0+)
-- coding: UTF-8 --
Filename : test.py
author by : www.runoob.com
User enters numbers
num1
=
input
(
'
Enter the first number:
'
)
num2
=
input
(
'
Enter the second number:
'
)
Sum
sum
=
float
(
num1
)
float
(
num2
)
Display the result
(
'
The sum of {0} and {1} is: {2}
'
.
format
(
num1
,
num2
,
sum
)
)
The output of the code above is:
输入第一个数字:1.5
输入第二个数字:2.5
数字 1.5 和 2.5 相加结果为: 4.0
In this example we sum two numbers entered by the user. The built-in input() function is used to get the user's input; input() returns a string, so we need the float() method to convert the string to a number.
For arithmetic on two numbers, summing uses the plus (+) operator; besides that there are minus (-), multiply (*), divide (/), floor division (//) and modulo (%). For more numeric operations see ourPython Number Operations。
We can also combine the operations above into a single line of code:
Example (Python 3.0+)
-- coding: UTF-8 --
Filename : test.py
author by : www.runoob.com
(
'
The sum of the two numbers is %.1f
'
%
(
float
(
input
(
'
Enter the first number:
'
)
)
float
(
input
(
'
Enter the second number:
'
)
)
)
)
The output of the code above is:
$ python test.py
输入第一个数字:1.5
输入第二个数字:2.5
两数之和为 4.0
Python3 Examples