Python 数据类型
Python's 核心数据类型: 数字, 字符串, 布尔值, 列表, tuples, dictionaries, and 设置.
你将学到
- 核心 numeric 类型: int and float
- 字符串 and 它们的大多数 useful 操作
- 布尔值 and truthy/falsy 值
- 集合: 列表, tuple, dict, and 设置
- 可变对比不可变类型 and 为什么它 matters
概念讲解
Numeric Types
Python has two main numeric types:
int— integers of arbitrary precision (no overflow!)float— floating-point numbers (IEEE 754 double)
count = 42 # int
price = 19.99 # float
big = 10 ** 100 # int — Python handles arbitrarily large integers
Strings
Strings are text, enclosed in single, double, or triple quotes:
name = "Ada"
greeting = 'Hello'
multi = """This is a
multi-line string"""
# F-strings (Python 3.6+) — the best way to format
message = f"Hello, {name}!"
Strings have useful methods: .upper(), .lower(), .strip(), .拆分(), .replace(), .startswith().
Booleans
is_active = True
is_deleted = False
Falsy values: 假, 0, 0.0, "", [], {}, 无. Everything else is truthy.
Collections
list — ordered, mutable
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
fruits[0] = "apricot" # mutable
tuple — ordered, immutable
point = (10, 20)
# point[0] = 5 # TypeError — tuples cannot be changed
dict — key-value pairs
user = {"name": "Ada", "age": 25}
user["email"] = "ada@示例.com" # add a key
print(user["name"])
set — unordered, unique elements
tags = {"python", "code", "学习"}
tags.add("fun")
tags.add("python") # no effect — already exists
Mutable vs Immutable
This is a crucial distinction:
- Immutable —
int,float,str,tuple,bool. Once created, their value cannot change. "更改" a string creates a new string. - Mutable —
列表,dict,设置. You can modify them in place.
# Strings are immutable
s = "hello"
s += " 世界" # creates a NEW string, s now points to it
# Lists are mutable
nums = [1, 2, 3]
nums.append(4) # modifies the SAME list
Checking Types
type(x) # returns the type
isinstance(x, int) # True if x is an int (or subclass)
Use isinstance() for type checks — it handles inheritance, while 类型() does not.
示例代码
# Numbers
count = 42
price = 19.99
big = 10 ** 50 # Python handles big integers natively
print(f"Count: {count}, Price: {price}, Big: {big}")
# Strings and f-strings
name = "Ada"
print(f"Hello, {name}!")
print(name.upper()) # ADA
print(name.replace("A", "E")) # Eda
# Lists — ordered and mutable
fruits = ["apple", "banana", "cherry"]
fruits.append("date")
print(fruits)
print(fruits[0]) # apple
print(fruits[-1]) # date (negative indexing)
# Dictionaries — key-value pairs
user = {"name": "Ada", "age": 25, "role": "admin"}
print(user["name"])
for key, value in user.items():
print(f" {key}: {value}")
# Tuples — immutable
point = (10, 20)
x, y = point # unpacking
print(f"Point: ({x}, {y})")
# Sets — unique elements
tags = {"python", "code", "python"} # duplicates removed
print(tags) # {'python', 'code'}
# Type checking
print(type(count)) # <class 'int'>
print(isinstance(name, str)) # True
Demonstrates 数字, f-字符串, 列表操作, dict iteration, tuple unpacking, 设置 deduplication, and 类型检查. 这些是 类型你 将 use 每个 day in Python.
动手试一试
- JSON Formatter
Python dicts and 列表映射 directly 到 JSON — 格式 and inspect 它们.
- CSV 到 JSON
Convert CSV 数据到 Python-样式 dicts — 常见数据任务.
常见错误
错误写法
Using 列表 as 默认实参 in 函数
正确做法
默认实参是 evaluated 一次, 不 on 每个 call. def f(x=[]): x.append(1) 将 accumulate 跨越 calls. Use def f(x=无): x = x or [] 相反.
错误写法
Expecting tuple 到是 可变如 列表
正确做法
Tuples 是不可变 — 你 cannot append, 移除, or reassign 元素. 如果你 需要到 修改序列, use 列表. Use tuples for fixed 集合如 坐标.
相关资源
相关代码片段
- 排序 Dictionary 通过值
practical 示例的 工作使用 dictionaries.
相关速查表
- Python Cheatsheet
所有数据类型使用方法 and 操作.
练习 Python 数据类型
13 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。