Python Number Sum

Document 对象参考手册Python3 Examples

The following example takes two numbers input by the user and calculates the sum of the two numbers:

Example (Python 3.0+)

# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.example.com # User inputs numbers num1 = input('Enter the first number:') num2 = input('Enter the second number:') # Sum sum = float(num1) + float(num2) # Display the calculation result print('The sum of {0} and {1} is: {2}'.format(num1, num2, sum))

Executing the above code produces the following output:

输入第一个数字:1.5
输入第二个数字:2.5
数字 1.5 和 2.5 相加结果为: 4.0

In this example, we sum two numbers entered by the user. We use the built-in function input() to get user input. input() returns a string, so we need to use the float() method to convert the string to a number.

For operations on two numbers, we use the plus (+) operator for addition. Besides this, there are also minus (-), multiplication (*), division (/), floor division (//), or modulo (%). For more numeric operations, you can view ourPython Numeric Operations。

We can also combine the above operations into a single line of code:

Example (Python 3.0+)

# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.example.com print('The sum of the two numbers is %.1f' %(float(input('Enter the first number:'))+float(input('Enter the second number:'))))

Executing the above code produces the following output:

$ python test.py 
输入第一个数字:1.5
输入第二个数字:2.5
两数之和为 4.0

Document 对象参考手册Python3 Examples

Other Extensions