I. What Is a Data Type
A data type is a mechanism by which a programming language classifies data. It describes the range of values a piece of data can take, how it is stored, which operations it supports, and the rules for using it.
For example:
age = 18
price = 99.9
name = "Alice"
is_active = True
These variables reference objects of different types:
| Variable | Data | Type |
|---|---|---|
age |
18 |
int |
price |
99.9 |
float |
name |
"Alice" |
str |
is_active |
True |
bool |
You can use the built-in function type() to check the type of an object:
print(type(18))
print(type(99.9))
print(type("Alice"))
print(type(True))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
1.1 What Data Types Do
Data types mainly solve the following problems:
- They define what the data means: they distinguish numbers, text, logical values, and other kinds of data.
- They determine the supported operations: integers can be used in arithmetic, and strings can be concatenated.
- They provide type constraints: some operations can only be applied to objects of a specific type.
- They support data conversion: data of different types can be converted using conversion functions.
- They help programs manage data: different types have different object behaviors and memory representations.
For example:
number = 10
text = "Python"
print(number + 5)
print(text + " Language")
Output:
15
Python Language
But:
print(number + text)
This raises a TypeError, because integers and strings do not support this kind of direct addition.
II. Overview of Python's Basic Data Types
Python has a number of built-in data types, which can be grouped by what the data is used for.
| Category | Data Type | Type Name | Main Purpose |
|---|---|---|---|
| Numeric types | Integer | int |
Represents whole numbers |
| Numeric types | Floating-point number | float |
Represents numbers with a decimal part |
| Numeric types | Complex number | complex |
Represents complex numbers |
| Boolean type | Boolean value | bool |
Represents true or false |
| Text type | String | str |
Represents text |
| Null type | Null value | NoneType |
Represents the absence of a value |
| Binary types | Bytes | bytes |
Represents an immutable sequence of bytes |
| Binary types | Byte array | bytearray |
Represents a mutable sequence of bytes |
| Binary types | Memory view | memoryview |
Provides a view of an underlying buffer |
In addition, Python also has built-in container types such as lists, tuples, dictionaries, and sets, which are covered in detail in the chapter on containers and data structures.
flowchart TD
A["Python Built-in Data Types"] --> B["Numeric Types"]
A --> C["Boolean Type"]
A --> D["Text Type"]
A --> E["Null Value Type"]
A --> F["Binary Types"]
B --> B1["int"]
B --> B2["float"]
B --> B3["complex"]
C --> C1["bool"]
D --> D1["str"]
E --> E1["NoneType"]
F --> F1["bytes"]
F --> F2["bytearray"]
F --> F3["memoryview"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B1 fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B2 fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B3 fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C1 fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D1 fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E1 fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F1 fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F2 fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F3 fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
III. Integer Type int
The integer type (Integer) is used to represent numeric values without a fractional part.
Python uses int to represent integers.
age = 18
temperature = -10
count = 0
print(type(age))
print(type(temperature))
print(type(count))
Output:
<class 'int'>
<class 'int'>
<class 'int'>
3.1 Characteristics of Integers
Python integers have the following characteristics:
- They can represent positive integers, negative integers, and zero.
- They do not contain a fractional part.
- They support arithmetic operations such as addition, subtraction, multiplication, and division.
- Integer precision is not directly limited by a fixed machine word size.
- Integer objects are limited by actual memory resources and implementation constraints.
Unlike the fixed-width integer types commonly found in C and Java, Python's int can represent very large integers.
For example:
number = 123456789012345678901234567890
print(number)
print(number * number)
Python can handle values far beyond the range of fixed 32-bit or 64-bit integers without requiring developers to manually switch integer types.
However, integers are not unlimited; their actual size is still limited by available memory and the runtime environment.
3.2 Integer Representations
Python supports integer representations in multiple bases.
| Base | Prefix | Example | Decimal Result |
|---|---|---|---|
| Binary | 0b |
0b1010 |
10 |
| Octal | 0o |
0o12 |
10 |
| Decimal | None | 10 |
10 |
| Hexadecimal | 0x |
0xA |
10 |
Example:
binary_number = 0b1010
octal_number = 0o12
decimal_number = 10
hex_number = 0xA
print(binary_number)
print(octal_number)
print(decimal_number)
print(hex_number)
Output:
10
10
10
10
You can also use bin(), oct(), and hex() to convert an integer into its string representation in the corresponding base:
number = 255
print(bin(number))
print(oct(number))
print(hex(number))
Output:
0b11111111
0o377
0xff
3.3 Integer Operations
Python integers support the usual arithmetic operations.
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 10 + 3 |
13 |
- |
Subtraction | 10 - 3 |
7 |
* |
Multiplication | 10 * 3 |
30 |
/ |
Division | 10 / 3 |
3.333... |
// |
Floor division | 10 // 3 |
3 |
% |
Modulus (remainder) | 10 % 3 |
1 |
** |
Exponentiation | 2 ** 3 |
8 |
Note that even when both operands are integers, / usually produces a float.
result = 10 / 2
print(result)
print(type(result))
Output:
5.0
<class 'float'>
//, on the other hand, performs floor division, rounding toward negative infinity:
print(10 // 3)
print(-10 // 3)
Output:
3
-4
Here, -10 // 3 does not simply truncate toward zero; it gives the largest integer that is no greater than the true quotient.
3.4 Common Uses of Integers
Integers are often used for:
- User ages.
- Product quantities.
- Order numbers.
- Loop counts.
- Data statistics.
- Status codes.
- Bitwise operations and low-level data processing.
IV. Floating-Point Type float
Floating-point numbers (Floating Point) are used to represent values that have a fractional part.
Python uses float to represent floating-point numbers.
price = 99.9
temperature = -3.5
rate = 0.25
print(type(price))
Output:
<class 'float'>
4.1 Characteristics of Floating-Point Numbers
Floating-point numbers have the following main characteristics:
- They can represent decimal values, not just whole numbers.
- They support the usual arithmetic operations.
- They typically use the IEEE 754 double-precision floating-point format.
- They have a large range, but limited significant precision.
- Some decimal fractions cannot be represented exactly by binary floating-point numbers.
4.2 Floating-Point Precision Issues
Consider a common problem:
a = 0.1
b = 0.2
print(a + b)
The output might be:
0.30000000000000004
Why isn't it exactly 0.3?
The reason is that computers generally represent floating-point numbers in binary, and some decimal fractions cannot be represented exactly as a finite-length binary fraction.
For example:
The binary representation repeats endlessly, so only an approximation can be stored.
This causes tiny errors in floating-point calculations.
4.3 Comparing Floating-Point Numbers
It is not recommended to use == directly to determine whether two computed floating-point numbers are equal.
a = 0.1 + 0.2
b = 0.3
print(a == b)
Output:
False
A more reasonable approach is to use math.isclose():
import math
a = 0.1 + 0.2
b = 0.3
print(math.isclose(a, b))
Output:
True
math.isclose() can determine whether two numeric values are close enough using relative and absolute tolerances.
import math
result = math.isclose(
0.1 + 0.2,
0.3,
rel_tol=1e-9,
abs_tol=1e-12,
)
print(result)
4.4 Scientific notation
Python supports using scientific notation to represent floating-point numbers.
a = 1.5e3
b = 2.5e-2
print(a)
print(b)
Output:
1500.0
0.025
Where:
1.5e3represents 1.5 \times 10^3.2.5e-2represents 2.5 \times 10^{-2}.
4.5 Special floating-point numbers
Python floating-point numbers can also represent some special values:
import math
positive_inf = float("inf")
negative_inf = float("-inf")
not_a_number = float("nan")
print(positive_inf)
print(negative_inf)
print(not_a_number)
print(math.isinf(positive_inf))
print(math.isnan(not_a_number))
Common special values:
| Special value | Meaning |
|---|---|
inf |
Positive infinity |
-inf |
Negative infinity |
nan |
Not a number |
Note:
value = float("nan")
print(value == value)
The result is:
False
NaN is not equal to any numeric value, including itself. To test for NaN, use math.isnan().
4.6 Why direct use of float is not recommended for financial calculations
In scenarios such as finance, payments, and accounting, binary approximation errors in floating-point numbers can cause problems.
For example:
price = 0.1 + 0.2
print(price)
For monetary calculations, decimal.Decimal is more recommended:
from decimal import Decimal
a = Decimal("0.1")
b = Decimal("0.2")
print(a + b)
Output:
0.3
Note that it is preferable to construct Decimal from a string, rather than directly from a float that already contains a precision error.
from decimal import Decimal
print(Decimal("0.1"))
print(Decimal(0.1))
The two results differ because the second approach preserves the approximate value actually stored by the floating-point number.
V. Complex Type: complex
A complex number is used to represent a numeric value that has a real part and an imaginary part.
In mathematics, a complex number is usually represented as:
Where:
- a represents the real part.
- b represents the imaginary part.
- i represents the imaginary unit, satisfying i^2=-1.
Python uses complex to represent complex numbers and j to represent the imaginary unit.
5.1 Creating a complex number
a = 3 + 4j
b = complex(3, 4)
print(a)
print(b)
print(type(a))
Output:
(3+4j)
(3+4j)
<class 'complex'>
5.2 Getting the real and imaginary parts
Complex number objects provide the real and imag attributes:
number = 3 + 4j
print(number.real)
print(number.imag)
Output:
3.0
4.0
5.3 Complex Number Operations
Python supports addition, subtraction, multiplication, division, and exponentiation for complex numbers.
a = 3 + 4j
b = 1 + 2j
print(a + b)
print(a - b)
print(a * b)
print(a / b)
Complex numbers do not support direct size comparison using < and >:
a = 3 + 4j
b = 1 + 2j
print(a > b)
This raises a TypeError.
5.4 Application Scenarios of Complex Numbers
Complex numbers are mainly used for:
- Signal processing.
- Circuit analysis.
- Fourier transforms.
- Mathematical calculations.
- Scientific computing.
- Physical modeling.
In ordinary business development, complex numbers are usually rarely used directly, but they are very important in scientific computing and engineering.
6. Boolean Type: bool
The Boolean type (Boolean) is used to represent the results of logical judgments.
Python uses bool to represent Boolean values, and there are only two built-in values:
TrueFalse
Note that the first letter must be capitalized.
is_active = True
is_deleted = False
print(type(is_active))
print(type(is_deleted))
Output:
<class 'bool'>
<class 'bool'>
6.1 Boolean Operations
Python provides three main logical operators:
| Operator | Meaning | Example |
|---|---|---|
and |
Logical AND | True and False |
or |
Logical OR | True or False |
not |
Logical NOT | not True |
Example:
a = True
b = False
print(a and b)
print(a or b)
print(not a)
Output:
False
True
False
6.2 Comparison Expressions Produce Boolean Values
age = 20
print(age >= 18)
print(age == 20)
print(age != 30)
Output:
True
True
True
The result of a comparison operation is usually a Boolean value.
Common comparison operators:
| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
6.3 bool Is a Subclass of int
There is an easily overlooked design in Python:
bool is a subclass of int.
print(issubclass(bool, int))
Output:
True
Therefore:
print(True + True)
print(False + 10)
Output:
2
10
Because in numeric contexts:
Trueis equivalent to1.Falseis equivalent to0.
Nevertheless, in ordinary business code, you should still understand Boolean values as logical data and should not casually use them as integers.
6.4 Truth Value Evaluation
In Python, not only True and False can be used for conditional checks; objects of other types can also participate in truth value testing.
The following objects are generally considered falsy:
NoneFalse- Numeric zero, such as
0and0.0 - Empty string
"" - Empty list
[] - Empty tuple
() - Empty dictionary
{} - Empty set
set()
Most other objects are considered truthy.
print(bool(0))
print(bool(1))
print(bool(""))
print(bool("Python"))
print(bool([]))
print(bool([1, 2]))
Output:
False
True
False
True
False
True
This is Python's truth value testing mechanism.
6.5 Practical Applications of Boolean Values
age = 20
has_permission = True
if age >= 18 and has_permission:
print("允许访问")
else:
print("拒绝访问")
The Boolean type is widely used for:
- Conditional checks.
- Loop control.
- Permission validation.
- State management.
- Business rule evaluation.
- Logical expressions.
7. String Type str
A string (String) is used to represent text data.
Python uses str to represent strings.
name = "Alice"
message = 'Hello Python'
print(type(name))
print(type(message))
Output:
<class 'str'>
<class 'str'>
7.1 Ways to Create Strings
Python supports several forms of string literals.
Single quotes:
name = 'Alice'
Double quotes:
name = "Alice"
Triple quotes:
message = """Hello
Python
World"""
Single quotes and double quotes are usually interchangeable.
Triple quotes make it easy to represent multiline strings and are also commonly used for docstrings.
7.2 Characteristics of Strings
Python strings have the following characteristics:
- They are a text type.
- They use Unicode characters to represent text.
- They support indexing and slicing.
- They support string concatenation and repetition.
- They are immutable objects.
- They provide a rich set of string processing methods.
7.3 String Indexing
Characters in a string can be accessed by index.
text = "Python"
print(text[0])
print(text[1])
print(text[-1])
Output:
P
y
n
Forward indexing starts at 0, and negative indexing starts at -1.
Character: P y t h o n
Forward: 0 1 2 3 4 5
Reverse: -6 -5 -4 -3 -2 -1
7.4 String Slicing
Slicing is used to obtain part of a string.
Basic form:
string[start:stop:step]
Where:
start: starting position, inclusive.stop: ending position, exclusive.step: step size.
Example:
text = "Python"
print(text[0:2])
print(text[2:5])
print(text[:3])
print(text[3:])
print(text[::-1])
Output:
Py
tho
Pyt
hon
nohtyP
7.5 Strings Are Immutable
Python strings are immutable objects.
This means that after a string is created, you cannot directly modify one of its characters.
text = "Python"
text[0] = "J"
Running it produces:
TypeError: 'str' object does not support item assignment
If you need to modify the content of a string, you should create a new string:
text = "Python"
text = "J" + text[1:]
print(text)
Output:
Jython
7.6 Common String Operations
Concatenation:
first = "Hello"
second = "Python"
result = first + " " + second
print(result)
Repetition:
print("Python " * 3)
Length:
text = "Python"
print(len(text))
Membership Test:
text = "Hello Python"
print("Python" in text)
print("Java" in text)
Case Conversion:
text = "Hello Python"
print(text.upper())
print(text.lower())
print(text.title())
Removing Leading and Trailing Whitespace:
text = " Python "
print(text.strip())
print(text.lstrip())
print(text.rstrip())
Replacement:
text = "Hello Java"
print(text.replace("Java", "Python"))
Splitting:
text = "Python,Java,Go"
print(text.split(","))
Joining:
languages = ["Python", "Java", "Go"]
print(",".join(languages))
7.7 String Formatting
Python provides several ways to format strings.
f-string:
name = "Alice"
age = 20
message = f"My name is {name}, I am {age} years old."
print(message)
format():
message = "My name is {}, I am {} years old.".format(
"Alice",
20,
)
print(message)
Percent-style formatting:
message = "My name is %s, I am %d years old." % (
"Alice",
20,
)
print(message)
In modern Python projects, f-strings are usually preferred because they are intuitive and easy to read.
8. Null Value Type NoneType
Python uses None to represent a null value.
None is the only built-in instance of the NoneType type.
value = None
print(value)
print(type(value))
Output:
None
<class 'NoneType'>
8.1 Meaning of None
None is commonly used to represent:
- There is currently no value.
- A function does not explicitly return a result.
- An object does not exist.
- Data that has not yet been set.
- An optional result is empty.
For example:
def say_hello():
print("Hello")
result = say_hello()
print(result)
Output:
Hello
None
Because the function does not use return to return another value, it returns None by default.
8.2 Using is to Check for None
Recommended:
value = None
if value is None:
print("当前没有值")
Not recommended:
if value == None:
print("当前没有值")
The reason is that None is a singleton object, so its identity should be checked with is.
8.3 The Difference Between None, Empty Strings, and Zero
These values are not the same in Python:
a = None
b = ""
c = 0
d = False
print(a is None)
print(b == "")
print(c == 0)
print(d is False)
Although they are all falsy in a boolean context, their meanings in business contexts differ:
| Value | Meaning |
|---|---|
None |
No value or does not exist |
"" |
An empty string exists |
0 |
Numeric zero |
False |
Logical false |
Do not conflate them in all business scenarios just because they are all falsy.
9. Binary Data Types
In addition to integers, floating-point numbers, and strings, Python also provides types specifically for handling binary data.
Common ones include:
bytesbytearraymemoryview
These types are very important in file processing, network communication, image processing, and low-level data operations.
9.1 bytes: Immutable Byte Sequences
bytes is used to represent an immutable sequence of bytes.
data = b"Python"
print(data)
print(type(data))
Output:
b'Python'
<class 'bytes'>
Each element in a bytes object is an integer ranging from 0 to 255.
data = b"ABC"
print(data[0])
print(data[1])
print(data[2])
Output:
65
66
67
9.2 Differences Between Strings and bytes
Strings and byte sequences are two different data types.
| Comparison Dimension | str | bytes |
|---|---|---|
| Content Represented | Unicode text | Raw byte sequence |
| Meaning of Elements | Characters corresponding to Unicode code points | Byte values from 0 to 255 |
| Mutability | Immutable | Immutable |
| Typical Use | Text processing | Files, networks, and binary data |
| Encoding Conversion | Via encode() | Via decode() |
Strings can be encoded into byte sequences:
text = "你好 Python"
data = text.encode("utf-8")
print(data)
print(type(data))
Byte sequences can be decoded into strings:
data = b"Hello Python"
text = data.decode("utf-8")
print(text)
print(type(text))
Complete conversion relationship: