Skip to content

Python3 Number

Python’s numeric data types are used to store numeric values.

The data types are immutable, meaning that changing the value of a numeric data type will reallocate memory space.

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

The syntax of 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) - Commonly referred to as an integer, 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 from Python2. Boolean (bool) is a subtype of integer.

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

  • Complex (complex) - A complex number consists of a real part and an imaginary part, expressed as a + bj or complex(a, b). Both the real part a and the imaginary part b are floats.

We can use hexadecimal and octal to represent integers:

>>> 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. A complex number consists of a real part and an imaginary part, expressed as a + bj or complex(a, b). Both the real part a and the imaginary part b are floats.

Sometimes, we need to convert between built-in data types. To convert data types, you just need to use the data type name as a function.

  • 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 part as x and the imaginary part as 0.

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

The following example converts the float variable a to an integer:

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

The Python interpreter can be used as a simple calculator. You can enter an expression into 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  # Always returns a float
1.6

Note: Floating-point operation results may vary on different machines.

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

>>> 17 / 3  # Integer division returns a float
5.666666666666667
>>>
>>> 17 // 3  # Integer division returns the result rounded down
5
>>> 17 % 3  # The % operator returns the remainder of division
2
>>> 5 * 3 + 2 
17

Note: // does not always return an integer type; it depends on the data types of the numerator and denominator.

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

The equals sign = is used to assign values to variables. After assignment, the interpreter does not display any result other than 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” (given a value) before use, otherwise an error will occur:

>>> n   # Attempt to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

When mixing different numeric types, integers are converted to floats:

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

In interactive mode, the last expression result 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 treated as a read-only variable by the user.


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

cmp(x, y)

Returns -1 if x < y, 0 if x == y, 1 if x > y. Deprecated in Python 3. Use (x>y)-(x<y) instead.
exp(x) Returns e raised to the power of x (ex), e.g., math.exp(1) returns 2.718281828459045
fabs(x) Returns the absolute value of a number as a float, e.g., math.fabs(-10) returns 10.0
floor(x) Returns 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) Returns the base-10 logarithm of x, e.g., math.log10(100) returns 2.0
max(x1, x2,...) Returns the maximum value of the given arguments. Arguments can be sequences.
min(x1, x2,...) Returns the minimum value of the given arguments. Arguments can be sequences.
modf(x) Returns the integer and fractional parts of x. Both parts have the same sign as x, and the integer part is represented as a float.
pow(x, y) The value of x**y.
round(x [,n])

Returns the rounded value of float x. If n is given, it represents the number of decimal places to round to.

More precisely, the value is rounded to the nearest end.

sqrt(x) Returns the square root of x.

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

Python includes the following commonly used random number functions:

Function Description
choice(seq) Randomly selects an element from a sequence, e.g., random.choice(range(10)) randomly picks an integer from 0 to 9.
randrange ([start,] stop [,step]) Retrieves a random number from a set that increments by a specified base within a specified range. The default base is 1.
random() Randomly generates the next real 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; Python will choose one for you.
shuffle(lst) Randomly sorts all elements of a sequence.
uniform(x, y) Randomly generates the next real number in the range [x,y].

Python includes the following trigonometric functions:

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

Constant Description
pi The mathematical constant pi (ratio of circumference to diameter, commonly represented as π)
e The mathematical constant e, the natural constant.