Python Number

Python Number data types are used to store numeric values.

Data types are immutable, which means that if you change the value of a Number data type, memory space will be reallocated.

In the following examples, Number objects are created when variables are assigned:

var1 = 1
var2 = 10

You can also use the del statement to delete some Number object references.

The syntax of the del statement is:

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

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

del var
del var_a, var_b

Python supports four different numeric types:

  • Integer (Int)- Usually called an integer or a whole number, it is a positive or negative integer without a decimal point.
  • Long integers- Integers of unlimited size, with an uppercase or lowercase L at the end.
  • Floating point real values- Floating point types consist of an integer part and a fractional part. Floating point types can also be expressed in scientific notation (2.5e2 = 2.5 x 102 = 250)
  • Complex numbers- Complex numbers consist of a real part and an imaginary part. They can be expressed as a + bj, or complex(a, b). Both the real part a and the imaginary part b of a complex number are floating point types.
intlongfloatcomplex
1051924361L0.03.14j
100-0x19323L15.2045.j
-7860122L-21.99.322e-36j
0800xDEFABCECBDAECBFBAEl32.3+e18.876j
-0490535633629843L-90.-.6545+0J
-0x260-052318172735L-32.54e1003e+26J
0x69-4721885298529L70.2-E124.53e-7j
  • Long integers can also use lowercase "L", but it is still recommended to use uppercase "L" to avoid confusion with the number "1". Python uses "L" to display long integers.
  • Python also supports complex numbers. Complex numbers consist of a real part and an imaginary part. They can be expressed as a + bj, or complex(a, b). Both the real part a and the imaginary part b of a complex number are floating point types.


Python Number Type Conversion

int(x [,base ])         将x转换为一个整数  
long(x [,base ])        将x转换为一个长整数  
float(x )               将x转换到一个浮点数  
complex(real [,imag ])  创建一个复数  
str(x )                 将对象 x 转换为字符串  
repr(x )                将对象 x 转换为表达式字符串  
eval(str )              用来计算在字符串中的有效Python表达式,并返回一个对象  
tuple(s )               将序列 s 转换为一个元组  
list(s )                将序列 s 转换为一个列表  
chr(x )                 将一个整数转换为一个字符  
unichr(x )              将一个整数转换为Unicode字符  
ord(x )                 将一个字符转换为它的整数值  
hex(x )                 将一个整数转换为一个十六进制字符串  
oct(x )                 将一个整数转换为一个八进制字符串  

Python math module, cmath module

The functions commonly used for mathematical operations in Python are basically in the math module and the cmath module.

The Python math module provides many mathematical operation functions for floating-point numbers.

The Python cmath module contains some functions for complex number operations.

The functions in the cmath module are basically the same as those in the math module. The difference is that the cmath module operates on complex numbers, while the math module performs mathematical operations.

To use math or cmath functions, you must first import them:

import math

View the contents of the math package:

>>> import math
>>> dir(math)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
>>>

The specific applications of each function will be introduced below.

View the contents of the cmath package

>>> import cmath
>>> dir(cmath)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
>>>

Example

>>> import cmath
>>> cmath.sqrt(-1)
1j
>>> cmath.sqrt(9)
(3+0j)
>>> cmath.sin(1)
(0.8414709848078965+0j)
>>> cmath.log10(100)
(2+0j)
>>>

Python 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, returns -1; if x == y, returns 0; if x > y, returns 1
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 floating-point number, 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) For example, 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 arguments, which can be a sequence.
min(x1, x2,...) Return the minimum value of the given arguments, which can be a sequence.
modf(x) Return the integer part and fractional part of x. The signs of both parts are the same as x, and the integer part is represented as a floating-point type.
pow(x, y)The value after x**y operation.
round(x [,n])Return the rounded value of floating-point x. If an n value is given, it represents the number of digits after the decimal point to round to.
sqrt(x) Return the square root of x.


Python Random Number Functions

Random numbers can be used in mathematics, games, security, and other fields. They are also often embedded in algorithms to improve algorithm efficiency and enhance program security.

Python includes the following commonly used random number functions:

FunctionDescription
choice(seq)Randomly select an element from the elements of a sequence, for example, random.choice(range(10)) randomly selects an integer from 0 to 9.
randrange ([start,] stop [,step]) Get 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 don't understand its principle, you don't need to set the seed specifically; Python will choose the seed for you.
shuffle(lst) Randomly sort all elements of a sequence.
uniform(x, y)Randomly generate the next real number, which is in the range [x, y].


Python Trigonometric Functions

Python includes the following trigonometric functions:

FunctionDescription
acos(x)Return the arc cosine radian value of x.
asin(x)Return the arc sine radian value of x.
atan(x)Return the arc tangent radian value of x.
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.


Python Mathematical Constants

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