Python3 Numbers (Number)
Python numeric data types are used to store numeric values.
Data types are immutable, which means that if the value of a numeric data type is changed, the memory space will be reallocated.
The following example creates Number objects when variables are assigned:
var1 = 1
var2 = 10
You can also use the del
statement to delete references to numeric objects.
The syntax for the del
statement is:
del var1[,var2[,var3[....,varN]]]
You can delete references to 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) - Typically referred to as an integer or whole number, it is a positive or negative whole number without a decimal point. Python3 integers have no size limit and can be used as Long types, so Python3 does not have the Long type of Python2. Boolean (bool) is a subtype of integer.
Floating Point (float) - A floating-point number consists of an integer part and a fractional part, and can also be represented using scientific notation (e.g., 2.5e2 = 2.5 x 10).
Complex (complex) - A complex number consists of a real part and an imaginary part and can be represented as
a + bj
orcomplex(a, b)
, where both the real parta
and the imaginary partb
are floating-point numbers.
We can represent integers using hexadecimal and octal:
>>> number = 0xA0F # Hexadecimal
>>> number
2575
>>> number = 0o37 # Octal
>>> number
31
int | float | complex |
---|---|---|
10 | 0.0 | 3.14j |
100 | 15.20 | 45.j |
-786 | -21.9 | 9.322e-36j |
080 | 32.3e+18 | .876j |
-0490 | -90. | -.6545+0J |
-0x260 | -32.54e100 | 3e+26J |
0x69 | 70.2E-12 | 4.53e-7j |
- Python supports complex numbers, which consist of a real part and an imaginary part and can be represented as
a + bj
orcomplex(a, b)
, where both the real parta
and the imaginary partb
are floating-point numbers.
Python Number Type Conversion
Sometimes, we need to convert the built-in types of data. To convert data types, you simply need to use the data type as the function name.
int(x) converts
x
to an integer.float(x) converts
x
to a floating-point number.complex(x) converts
x
to a complex number with the real partx
and the imaginary part0
.complex(x, y) converts
x
andy
to a complex number with the real partx
and the imaginary party
.x
andy
are numeric expressions.
The following example converts a floating-point variable a
to an integer:
>>> a = 1.0
>>> int(a)
1
Python Numeric Operations
The Python interpreter can act as a simple calculator; you can type an expression into the interpreter, and it will output the value of the expression.
The syntax for expressions is straightforward: +
, -
, *
, and /
work 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 # Always returns a floating-point number
1.6
Note: The results of floating-point operations may vary on different machines.
In integer division, the division /
always returns a floating-point number. If you only want the integer result, discarding any fractional part, you can use the //
operator:
>>> 17 / 3 # Integer division returns a floating-point number
5.666666666666667
>>>
>>> 17 // 3 # Integer division returns the floor result
5
>>> 17 % 3 # % operator returns the remainder of the division
2
>>> 5 * 3 + 2
17
Note: The result of //
is not necessarily an integer type; it depends on the data types of the numerator and the denominator.
>>> 7 // 2
3
>>> 7.0 // 2
3.0
>>> 7 // 2.0
3.0
>>>
The equals sign =
is used to assign a value to a variable. After the assignment, the interpreter will not display any results except for the next prompt.
>>> width = 20
>>> height = 5*9
>>> width * height
900
Python can use the **
operator for exponentiation:
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
Variables must be "defined" (assigned a value) before they are used, or an error will occur:
>>> n # Trying to access an undefined variable
Traceback (most recent call last):
When different types of numbers are mixed in operations, integers are converted to floating-point numbers:
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
In interactive mode, the result of the last expression output 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 considered read-only by the user.
Mathematical Functions
Function | Return Value (Description) |
---|---|
abs(x) | Returns the absolute value of the number, e.g., abs(-10) returns 10 |
ceil(x) | Returns the ceiling of the 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. Deprecated in Python 3, use (x>y)-(x<y) instead. |
exp(x) | Returns e raised to the power of x (e^x), e.g., math.exp(1) returns 2.718281828459045 |
fabs(x) | Returns the absolute value of the number, e.g., math.fabs(-10) returns 10.0 |
floor(x) | Returns the floor of the 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) | Returns the base-10 logarithm of x, e.g., math.log10(100) returns 2.0 |
max(x1, x2,...) | Returns the largest value among the given arguments, which can be a sequence. |
min(x1, x2,...) | Returns the smallest value among the given arguments, which can be a sequence. |
modf(x) | Returns the integer and fractional parts of x, both with the same sign as x, and the integer part as a float. |
pow(x, y) | The value of x**y. |
round(x [,n]) | Returns the rounded value of x to n digits after the decimal point. The exact rounding direction is towards the nearest value. |
sqrt(x) | Returns the square root of x. |
Random Number Functions
Random numbers are used in mathematics, gaming, security, and other fields. They are often embedded in algorithms to improve efficiency and enhance program security.
Python includes the following common random number functions:
Function | Description |
---|---|
choice(seq) | Randomly selects an element from a sequence, e.g., random.choice(range(10)) selects an integer from 0 to 9. |
randrange ([start,] stop [,step]) | Gets a random number from a specified range, incremented by a specified base, which defaults to 1. |
random() | Generates the next random number in the range [0,1). |
seed([x]) | Changes the seed of the random number generator. If you don't understand the principle, you don't need to set the seed specifically; Python will choose it for you. |
shuffle(lst) | Randomly shuffle all elements of the sequence |
uniform(x, y) | Generate the next random floating-point number within the range [x, y] |
Trigonometric Functions
Python includes the following trigonometric functions:
Function | Description |
---|---|
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 y/x, using the signs of both to determine the quadrant of the return value |
cos(x) | Return the cosine of x radians |
hypot(x, y) | Return the Euclidean norm, sqrt(xx + yy) |
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
Constant | Description |
---|---|
pi | Mathematical constant pi (π, the ratio of a circle's circumference to its diameter) |
e | Mathematical constant e, the base of the natural logarithm |