Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python3 Numbers


May 10, 2021 Python3


Table of contents


Python numeric operations

The Python interpreter can be used as a simple calculator: you can enter an expression in the interpreter that outputs the value of the expression.

The syntax + an * expression is straight- and - , / and / as in many other languages, such as Pascal or C; For example:

>>> 2 + 2
4
>>> 50 - 5 * 6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # 总是返回一个浮点数
1.6

Note: The results of floating-point operations may be different on different machines. We'll then cover controlling the output of floating-point operations.

In integer division, division / always returns a floating point, and if you only want to get the result of an integer and discard the possible fractional part, you can use // :

>>> 17 / 3  # 整数除法返回浮点型
5.666666666666667
>>>
>>> 17 // 3  # 整数除法返回向下取整后的结果
5
>>> 17 % 3  # %操作符返回除法的余数
2
>>> 5 * 3 + 2 
17

Note: // of integer types is obtained is related to the data type of the denominator molecule.

>>> 7//2
3
>>> 7.0//2
3.0
>>> 7//2.0
3.0
>>> 

The equal sign = used to assign a value to a variable. After the assignment, the interpreter does not display any results except for the next prompt.

>>> width = 20
>>> height = 5*9
>>> width * height
900

Python can use ** to perform power operations:

>>> 5 ** 2  # 5 的平方
25
>>> 2 ** 7  # 2的7次方
128

The variable must be "defined" (that is, given a value to the variable) before it can be used, or an error will occur:

>>> # 尝试访问一个未定义的变量
... n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

Floating points are fully supported;

>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5

In interactive mode, the result of the last expression that is output is assigned to the variable . This makes it easier for you to use Python as a desktop calculator for subsequent calculations, such as:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

Here, the variable should be treated as a read-only variable by the user. Don't explicitly assign it a value -- you'll create a separate local variable with the same name and mask the functionality of the built-in variable.