I. Overview of Numeric Types
Numeric types are used to represent and process numerical values in mathematics. Python has three built-in main numeric types:
| Type | Meaning | Typical Use | Mutability |
|---|---|---|---|
int |
Integer | Counting, indexing, integer arithmetic | Immutable |
float |
Floating-point number | Decimals, measurements, scientific computing | Immutable |
complex |
Complex number | Signal processing, mathematical computing, engineering computing | Immutable |
The three types have different ways of representing values and different operational characteristics.
a = 100
b = 3.14
c = 2 + 3j
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'complex'>
Numeric types in Python share the following characteristics:
- They are all objects, each with its own type and methods.
- They are all immutable objects; numeric operations usually produce new objects.
- They support a rich set of arithmetic operations.
- They can be converted between types using built-in functions.
- Different numeric types can be mixed in operations according to certain rules.
Note that bool is also a subclass of int, so boolean values can behave as 1 and 0 in numeric operations.
print(isinstance(True, int)) # True
print(True + 1) # 2
print(False + 1) # 1
II. The Integer Type int
2.1 What Is int
int is Python's integer type, used to represent whole numbers with no fractional part.
a = 10
b = -20
c = 0
print(type(a)) # <class 'int'>
print(type(b)) # <class 'int'>
print(type(c)) # <class 'int'>
Python integers support positive numbers, negative numbers, and zero.
Unlike many other programming languages, Python's plain integers have no fixed 32-bit or 64-bit range limit. As long as available memory allows, integers can grow to very large values.
a = 123456789012345678901234567890
b = 2 ** 1000
print(a)
print(b)
print(len(str(b)))
This means Python does not automatically suffer fixed-width integer overflow when an integer exceeds 2^31 - 1 or 2^63 - 1.
However, integers are not truly infinite: the largest integer that can actually be represented is still constrained by machine memory, implementation details, and resource limits.
2.2 Different Bases for Integers
Python supports integer representation in several bases.
| Base | Prefix | Example | Decimal Result |
|---|---|---|---|
| Binary | 0b |
0b1010 |
10 |
| Octal | 0o |
0o12 |
10 |
| Decimal | None | 10 |
10 |
| Hexadecimal | 0x |
0xA |
10 |
Example:
binary_num = 0b1010
octal_num = 0o12
decimal_num = 10
hex_num = 0xA
print(binary_num) # 10
print(octal_num) # 10
print(decimal_num) # 10
print(hex_num) # 10
Numbers in different bases are ultimately all interpreted as Python int objects.
The following functions can be used for base conversion:
number = 255
print(bin(number)) # 0b11111111
print(oct(number)) # 0o377
print(hex(number)) # 0xff
These functions return strings, not integers.
If you want to parse a string according to a specified base, you can use int():
print(int("1010", 2)) # 10
print(int("12", 8)) # 10
print(int("FF", 16)) # 255
2.3 Arithmetic Operations on Integers
Python integers support the common arithmetic operations.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Addition | 10 + 3 |
13 |
- |
Subtraction | 10 - 3 |
7 |
* |
Multiplication | 10 * 3 |
30 |
/ |
True division | 10 / 3 |
3.333... |
// |
Floor division | 10 // 3 |
3 |
% |
Modulo | 10 % 3 |
1 |
** |
Exponentiation | 10 ** 3 |
1000 |
Example:
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.3333333333333335
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 1000
There are two things here that are easy to confuse:
First, / and // are different.
/ performs true division; even if both operands are integers, the result is usually a float.
print(10 / 2) # 5.0
print(10 // 2) # 5
print(type(10 / 2)) # <class 'float'>
print(type(10 // 2)) # <class 'int'>
Second, // rounds down — it does not simply chop off the decimal part.
print(7 // 2) # 3
print(-7 // 2) # -4
print(7.0 // 2) # 3.0
For negative numbers, rounding down means the result is rounded toward negative infinity.
Therefore:
print(-7 // 2) # -4
print(int(-7 / 2)) # -3
The two results are different.
2.4 Bitwise Operations on Integers
Python's int also supports bitwise operations, which are commonly used in low-level data processing, permission flags, status bits, and algorithm implementations.
| Operator | Meaning | Example |
|---|---|---|
& |
Bitwise AND | 5 & 3 |
\| |
Bitwise OR | 5 \| 3 |
^ |
Bitwise XOR | 5 ^ 3 |
~ |
Bitwise NOT | ~5 |
<< |
Left shift | 5 << 1 |
>> |
Right shift | 5 >> 1 |
Example:
a = 5 # binary 0101
b = 3 # binary 0011
print(a & b) # 1
print(a | b) # 7
print(a ^ b) # 6
print(~a) # -6
print(a << 1) # 10
print(a >> 1) # 2
Python integers have arbitrary precision, so bitwise operations are not limited to a fixed 32-bit or 64-bit integer width.
2.5 Common Functions Related to Integers
| Function | Purpose | Example |
|---|---|---|
int() |
Convert to an integer | int("123") |
abs() |
Calculate the absolute value | abs(-10) |
pow() |
Calculate a power | pow(2, 3) |
divmod() |
Calculate the quotient and remainder at the same time | divmod(10, 3) |
bin() |
Convert to a binary string | bin(10) |
oct() |
Convert to an octal string | oct(10) |
hex() |
Convert to a hexadecimal string | hex(10) |
Among them, divmod() is very useful when you need to obtain both the quotient and the remainder at the same time.
quotient, remainder = divmod(17, 5)
print(quotient) # 3
print(remainder) # 2
Its result is equivalent to calculating 17 // 5 and 17 % 5 at the same time.
3. Floating-Point Type float
3.1 What Is float
float is Python's floating-point type, used to represent numeric values with a fractional part.
a = 3.14
b = -0.5
c = 2.0
print(type(a)) # <class 'float'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'float'>
Even if a number has no fractional part, as long as its literal contains a decimal point, it is still a floating-point number.
a = 10
b = 10.0
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
3.2 Scientific Notation for Floating-Point Numbers
Python supports using scientific notation to represent floating-point numbers.
a = 1.5e3
b = 2.5e-3
c = 3E2
print(a) # 1500.0
print(b) # 0.0025
print(c) # 300.0
The basic form of scientific notation is:
a × 10^n
Where:
arepresents the significant digits.nrepresents the decimal exponent.eorEindicates multiplication by a power of 10.
Scientific notation is suitable for representing very large or very small values and is very common in scientific computing, statistical analysis, and engineering calculations.
3.3 Precision Issues with Floating-Point Numbers
One of the most important characteristics of floating-point numbers is that they usually cannot represent all decimal fractions exactly.
Python's common float implementation is based on IEEE 754 double-precision binary floating point and typically uses 64-bit storage.
Its structure can be summarized as:
- 1 sign bit.
- 11 exponent bits.
- 52 mantissa storage bits, plus an implicit significand bit.
Binary floating-point numbers can exactly represent many binary fractions, but decimal fractions such as 0.1 usually cannot be represented exactly with a finite number of binary fractional digits.
Therefore, the following occurs:
a = 0.1
b = 0.2
print(a + b) # 0.30000000000000004
This is not a calculation error in Python, but a normal phenomenon caused by the limited precision of binary floating-point representation.
You can observe this with the following example:
print(format(0.1, ".20f"))
print(format(0.2, ".20f"))
print(format(0.3, ".20f"))
The output will show the decimal form of the floating-point number's internal approximation.
3.4 Why Floating-Point Numbers Cannot Be Compared Directly
Because floating-point numbers have representation errors, directly using == to compare two calculation results may produce unexpected results.
a = 0.1 + 0.2
b = 0.3
print(a == b) # False
When you need to determine whether two floating-point numbers are close enough, you can use math.isclose():
import math
a = 0.1 + 0.2
b = 0.3
print(math.isclose(a, b)) # True
math.isclose() supports two main parameters:
rel_tol: relative tolerance.abs_tol: absolute tolerance.
import math
a = 0.0000001
b = 0.0000002
print(
math.isclose(
a,
b,
rel_tol=1e-9,
abs_tol=1e-8
)
)
Relative tolerance is suitable for comparing numbers of different magnitudes, while absolute tolerance is suitable for values close to zero.
In practice, you should choose an appropriate tolerance based on the error range allowed by the business logic rather than blindly using the default values.
3.5 Special Floating-Point Values
Python floating-point numbers support some special values.
| Special value | Meaning |
|---|---|
inf |
Positive infinity |
-inf |
Negative infinity |
nan |
Not a Number (NaN) |
You can create these values with float():
positive_inf = float("inf")
negative_inf = float("-inf")
not_a_number = float("nan")
print(positive_inf)
print(negative_inf)
print(not_a_number)
You can also use the math module to test them:
import math
a = float("inf")
b = float("nan")
c = 3.14
print(math.isinf(a)) # True
print(math.isnan(b)) # True
print(math.isfinite(c)) # True
Pay special attention to the following:
An equality comparison between NaN and any numeric value, including itself, always returns False.
x = float("nan")
print(x == x) # False
print(x != x) # True
Therefore, to test for NaN, use math.isnan(), not ==.
3.6 Common Floating-Point Functions
| Function | Purpose | Example |
|---|---|---|
float() |
Convert to floating point | float("3.14") |
round() |
Round half to even | round(2.5) |
abs() |
Absolute value | abs(-3.14) |
math.floor() |
Round down | math.floor(3.8) |
math.ceil() |
Round up | math.ceil(3.2) |
math.trunc() |
Truncate toward zero | math.trunc(-3.8) |
math.isclose() |
Approximate comparison | math.isclose(0.1 + 0.2, 0.3) |
math.isfinite() |
Check whether finite | math.isfinite(3.14) |
Example:
import math
print(round(3.14159, 2)) # 3.14
print(math.floor(3.8)) # 3
print(math.ceil(3.2)) # 4
print(math.trunc(-3.8)) # -3
Note that when a value is exactly halfway between two representable results, Python's round() uses the ties-to-even (round half to even) rule.
print(round(2.5)) # 2
print(round(3.5)) # 4
print(round(4.5)) # 4
In addition, binary representation errors in floating-point numbers can also affect rounding results.
3.7 Why You Should Not Use float Directly for Financial Calculations
Floating-point numbers are suitable for approximate numerical calculations, but financial applications usually require strict control of decimal precision.
For example:
price = 19.9
quantity = 3
total = price * quantity
print(total) # 59.699999999999996
If you use float directly to handle monetary amounts, it may introduce hard-to-detect precision issues.
Python provides decimal.Decimal for exact decimal arithmetic.
from decimal import Decimal
price = Decimal("19.9")
quantity = Decimal("3")
total = price * quantity
print(total) # 59.7
Note that you should prefer creating a Decimal from a string, to avoid precision errors caused by converting through float first.
from decimal import Decimal
# Recommended
a = Decimal("0.1")
b = Decimal("0.2")
print(a + b) # 0.3
# Not recommended
c = Decimal(0.1)
print(c)
Decimal is not a replacement for float. It is suitable for scenarios that are sensitive to decimal precision, while scientific computing will usually still use float.
IV. Complex Type complex
4.1 What is complex
A complex number is a value made up of a real part and an imaginary part, with the mathematical form:
z = a + bj
Where:
ais the real part.bis the coefficient of the imaginary part.jis the imaginary unit, satisfyingj² = -1.
Python uses j or J to represent the imaginary unit.
a = 2 + 3j
b = 4 - 5j
c = 6j
print(type(a)) # <class 'complex'>
print(type(b)) # <class 'complex'>
print(type(c)) # <class 'complex'>
Python uses j instead of the i commonly used in mathematics, mainly because i is often used as the symbol for electric current in engineering.
4.2 Creating Complex Numbers
There are several ways to create a complex number.
Method 1: Use a complex literal directly
z = 2 + 3j
print(z) # (2+3j)
Method 2: Use complex()
z = complex(2, 3)
print(z) # (2+3j)
The two arguments of complex(real, imag) represent the real part and the imaginary part, respectively.
Method 3: Use real and imaginary numbers in an operation
real = 2
imag = 3
z = real + imag * 1j
print(z) # (2+3j)
Note that you cannot use j directly as an ordinary variable. It is the imaginary marker in Python complex literals.
4.3 Getting the Real and Imaginary Parts of a Complex Number
Python's complex objects provide the real and imag attributes.
z = 2 + 3j
print(z.real) # 2.0
print(z.imag) # 3.0
Both attributes return floating-point numbers.
You can also use conjugate() to get the conjugate of a complex number.
z = 2 + 3j
print(z.conjugate()) # (2-3j)
The conjugate form of a complex number is:
z = a + bj
Conjugate = a - bj
4.4 Arithmetic Operations on Complex Numbers
Python supports addition, subtraction, multiplication, division, and exponentiation of complex numbers.
a = 2 + 3j
b = 1 + 2j
print(a + b) # (3+5j)
print(a - b) # (1+1j)
print(a * b) # (-4+7j)
print(a / b) # (1.6-0.2j)
print(a ** 2) # (-5+12j)
Complex multiplication follows the mathematical rule:
(a + bj)(c + dj)
= (ac - bd) + (ad + bc)j
For example:
(2 + 3j)(1 + 2j)
= 2 + 4j + 3j + 6j²
= 2 + 7j - 6
= -4 + 7j
Python performs complex arithmetic automatically; there is no need to manually split the real and imaginary parts.
4.5 Modulus and Argument of a Complex Number
A complex number can be viewed as a point on the complex plane.
For:
z = a + bj
Its modulus represents the distance from that point to the origin:
|z| = √(a² + b²)
Python can use abs() to calculate the modulus of a complex number.
z = 3 + 4j
print(abs(z)) # 5.0
If you need to calculate the argument of a complex number, you can use cmath.phase():
import cmath
z = 3 + 4j
print(cmath.phase(z))
The argument is expressed in radians.
You can also use cmath.polar() to obtain both the modulus and the argument at the same time:
import cmath
z = 3 + 4j
r, phi = cmath.polar(z)
print(r) # 5.0
print(phi)
If you want to recover a complex number from polar form, you can use cmath.rect():
import cmath
z = cmath.rect(5, 0.927295218)
print(z)
4.6 Comparison Restrictions on Complex Numbers
Python allows equality and inequality comparisons for complex numbers, but does not support ordering comparisons between complex numbers.
a = 2 + 3j
b = 1 + 2j
print(a == b) # False
print(a != b) # True
# The following operations will raise TypeError
# print(a > b)
# print(a < b)
The reason is that complex numbers, unlike real numbers, do not have a natural total order.
If you need to compare complex numbers by size, you must first define the business rule, for example comparing the modulus, real part, or imaginary part:
a = 2 + 3j
b = 4 + 1j
print(abs(a) > abs(b))
Here, the comparison is between the moduli of two complex numbers, not the size of the complex numbers themselves.
4.7 complex and the cmath Module
Python's math module is primarily intended for real-number operations.
When calculations involve complex numbers, the cmath module should be used.
| Module | Primary objects handled | Common functions |
|---|---|---|
math |
Real numbers | sqrt(), sin(), cos() |
cmath |
Complex numbers | sqrt(), sin(), cos(), phase() |
For example:
import math
import cmath
# math.sqrt(-1) will raise ValueError
# print(math.sqrt(-1))
# cmath.sqrt() can handle negative numbers
print(cmath.sqrt(-1)) # 1j
Complex-number operations are commonly used in:
- Digital signal processing.
- Circuit and alternating current analysis.
- Fourier transforms.
- Control systems.
- Mathematical modeling.
- Scientific and engineering computing.
V. Conversion Between the Three Numeric Types
Python provides three built-in constructors, int(), float(), and complex(), for creating the corresponding numeric types.
5.1 int() Conversion
int() can convert a numeric value or string that conforms to the rules into an integer.
print(int(3.9)) # 3
print(int(-3.9)) # -3
print(int("123")) # 123
print(int("1010", 2)) # 10
Things to note:
- When a float is converted to an integer, it is truncated toward zero rather than rounded.
- The string must conform to the integer format.
- A string containing a decimal point cannot be converted directly to an integer.
print(int(3.9)) # 3
print(int("3")) # 3
# The following operation will raise ValueError
# print(int("3.9"))
If you need to parse the decimal first and then convert it to an integer, you can first convert it to float:
number = int(float("3.9"))
print(number) # 3
5.2 float() Conversion
float() can convert integers, numeric strings, and some other numeric values into floats.
print(float(10)) # 10.0
print(float("3.14")) # 3.14
print(float("1e3")) # 1000.0
For strings that cannot be parsed, a ValueError will be raised.
# print(float("hello"))