Python3 Numbers (Number)

The Python numeric data type is used to store numeric values.

Data types are not allowed to be changed, which means that if you change the value of a numeric data type, memory space will be reallocated.

In the following example, a Number object is created when a variable is assigned:

var1 = 1
var2 = 10

You can also use the del statement to delete references to some number objects.

The syntax of the del statement is:

del var1[,var2[,var3[....,varN]]]

You can delete references to a single or multiple objects using the del statement, for example:

del var
del var_a, var_b

Python supports three different numeric types:

  • Integer (int)- Usually called an integer or whole number, it is a positive or negative integer without a decimal point. Python3 integers have no size limit and can be used as a Long type, so Python3 does not have the Long type of Python2. Boolean (bool) is a subtype of integer.

  • Float (float)- Float consists of an integer part and a fractional part. Float can also be expressed in scientific notation (2.5e2 = 2.5 x 102 = 250)

  • Complex (complex)- A complex number consists of a real part and an imaginary part. It can be expressed as a + bj, or complex(a,b). The real part a and imaginary part b of a complex number are both floating-point types.

We can use hexadecimal and octal to represent integers:

>>> number = 0xA0F # 十六进制
>>> number
2575

>>> number=0o37 # 八进制
>>> number
31
intfloatcomplex
100.03.14j
10015.2045.j
-786-21.99.322e-36j
08032.3e+18.876j
-0490-90.-.6545+0J
-0x260-32.54e1003e+26J
0x6970.2E-124.53e-7j
  • Python supports complex numbers. A complex number consists of a real part and an imaginary part. It can be expressed as a + bj, or complex(a,b). The real part a and imaginary part b of a complex number are both floating-point types.


Python Number Type Conversion

Sometimes, we need to convert the built-in types of data. For data type conversion, you only need to use the data type as the function name.

  • int(x)Convert x to an integer.

  • float(x)Convert x to a float.

  • complex(x)Convert x to a complex number, with the real part x and the imaginary part 0.

  • complex(x, y)Convert x and y to a complex number, with the real part x and the imaginary part y. x and y are numeric expressions.

The following example converts float variable a to an integer:

>>> a = 1.0
>>> int(a)
1

Python Number Operations

The Python interpreter can act as a simple calculator. You can enter an expression in the interpreter, and it will output the value of the expression.

The syntax of expressions is straightforward:+, -, *and/, just like in 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.

In integer division, division/always returns a float. If you only want an integer result, discarding the possible fractional part, you can use the operator// :

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

Note://The result is not necessarily an integer type; it depends on the data types of the denominator and numerator.

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

The equal sign=is used to assign values to variables. After assignment, except for the next prompt, the interpreter will not display any result.

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

Python can use**operator for exponentiation:

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

Variables must be "defined" (i.e., assigned a value) before use, otherwise an error will occur:

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

When different types of numbers are mixed in operations, integers will be converted to floats:

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

In interactive mode, the result of the last printed expression is assigned to the variable_ . For example:

>>> 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.



Mathematical Functions

FunctionReturn value (Description)
abs(x)Return the absolute value of a number, e.g., abs(-10) returns 10
ceil(x) Return the ceiling integer of a number, e.g., math.ceil(4.1) returns 5

cmp(x, y)

If x < y return -1, if x == y return 0, if x > y return 1.Deprecated in Python 3, use (x>y)-(x<y) instead。
exp(x) Return e raised to the power of x (ex), e.g., math.exp(1) returns 2.718281828459045
fabs(x)Return the absolute value of a number as a float, e.g., math.fabs(-10) returns 10.0
floor(x) Return the floor integer of a number, e.g., math.floor(4.9) returns 4
log(x) e.g., math.log(math.e) returns 1.0, math.log(100,10) returns 2.0
log10(x) Return the base-10 logarithm of x, e.g., math.log10(100) returns 2.0
max(x1, x2,...) Return the maximum value of the given parameters; the parameters can be a sequence.
min(x1, x2,...) Return the minimum value of the given parameters; the parameters can be a sequence.
modf(x) Return the integer part and fractional part of x. Both parts have the same sign as x, and the integer part is represented as a float.
pow(x, y)The value after the x**y operation.
round(x [,n])

Return the rounded value of float x. If an n value is given, it represents the number of digits after the decimal point.

Actually, to be precise, the retained value is kept to the side closer to the higher-order digit.

sqrt(x) Return the square root of x.


Random Number Functions

Random numbers can be used in fields such as mathematics, games, and security. They are often embedded in algorithms to improve algorithm efficiency and enhance the security of programs.

Python includes the following commonly used random number functions:

FunctionDescription
choice(seq)Randomly select an element from the elements of a sequence, e.g., random.choice(range(10)) randomly selects an integer from 0 to 9.
randrange ([start,] stop [,step]) Obtain a random number from a set that increments by a specified base within a specified range; the default base value is 1.
random() Randomly generate the next real number, which is in the range [0,1).
seed([x]) Change the seed of the random number generator. If you do not understand its principle, you do not need to set the seed specifically; Python will choose the seed for you.
shuffle(lst) Randomly sort all elements of the sequence.
uniform(x, y)Randomly generate the next real number, which is in the range [x,y].


Trigonometric Functions

Python includes the following trigonometric functions:

FunctionDescription
acos(x)Return the arc cosine of x, in radians.
asin(x)Return the arc sine of x, in radians.
atan(x)Return the arc tangent of x, in radians.
atan2(y, x)Return the arc tangent of the given X and Y coordinate values.
cos(x)Return the cosine of x radians.
hypot(x, y)Return the Euclidean norm sqrt(x*x + y*y).
sin(x)Return the sine of x radians.
tan(x)Return the tangent of x radians.
degrees(x)Convert radians to degrees, e.g., degrees(math.pi/2) returns 90.0
radians(x)Convert degrees to radians


Mathematical Constants

ConstantDescription
piMathematical constant pi (circumference ratio, generally represented as π)
eMathematical constant e, e is the natural constant (natural constant).
Other Extensions