Python 基础知识
基础语法
一、标识符
- 第一个字符必须以字母(a-z, A-Z)或下划线 _ 。
- 标识符的其他的部分由字母、数字和下划线组成。
- 标识符对大小写敏感,count 和 Count 是不同的标识符。
- 标识符对长度无硬性限制,但建议保持简洁(一般不超过 20 个字符)。
- 禁止使用保留关键字,如 if、for、class 等不能作为标识符。
Python 3 允许使用 Unicode 字符作为标识符,可以用中文作为变量名。
二、关键字
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
三、注释
3.1 普通注释
print("Hello, World!") # 这是一个单行注释
'''
这是多行注释,用三个单引号
这是多行注释,用三个单引号
这是多行注释,用三个单引号
'''
- 多行注释实际上就是一个字符串,所以连续三个引号可以用来做多行输入的字符串;
- 另外,多行注释不允许嵌套,这会导致语法错误
3.2 python-docstring
Python 的文档字符串(Docstring)是内置的,可通过 __doc__ 属性在运行时直接访问,支持三种主流风格(Sphinx/Google/NumPy),详见 python-docstring。
四、行与缩进
- Python 使用缩进结构来区分代码块,而不是像其他高级语言那样使用
{} - 缩进最好是用制表键来完成,空格数不一致会导致运行错误
- 用反斜杠
\来实现多行输入
total = item_one + \
item_two + \
item_three
- 在序列容器中则可以直接换行而不是使用
\
五、运算符
5.1 算术运算符
| 运算符 | 实例 | 描述 |
|---|---|---|
| + | a + b 输出结果 31 | 加 - 两个对象相加 |
| - | a - b 输出结果 -11 | 减 - 得到负数或是一个数减去另一个数 |
| * | a * b 输出结果 210 | 乘 - 两个数相乘或是返回一个被重复若干次的字符串 |
| / | b / a 输出结果 2.1 | 除 - x 除以 y |
| % | b % a 输出结果 1 | 取模 - 返回除法的余数 |
| ** | a**b 为 10 的 21 次方 | 幂 - 返回 x 的 y 次幂 |
| // | 9//2=4 -9//2=-5 | 取整除 - 往小的方向取整数 |
5.2 比较运算符(优先级高于逻辑运算符)
| 运算符 | 描述 | 实例 |
|---|---|---|
| == | 等于 - 比较对象是否相等 | (a == b) 返回 False。 |
| != | 不等于 - 比较两个对象是否不相等 | (a != b) 返回 True。 |
| > | 大于 - 返回 x 是否大于 y | (a > b) 返回 False。 |
| < | 小于 - 返回 x 是否小于 y。所有比较运算符返回 1 表示真,返回 0 表示假。这分别与特殊的变量 True 和 False 等价。注意,这些变量名的大写。 | (a < b) 返回 True。 |
| >= | 大于等于 - 返回 x 是否大于等于 y。 | (a >= b) 返回 False。 |
| <= | 小于等于 - 返回 x 是否小于等于 y。 | (a <= b) 返回 True。 |
5.3 逻辑运算符
| 运算符 | 逻辑表达式 | 描述 | 实例(a=10,b=20) |
|---|---|---|---|
| and | x and y | 布尔 " 与 " - 如果 x 为 False,x and y 返回 x 的值,否则返回 y 的计算值。 | (a and b) 返回 20。 |
| or | x or y | 布尔 " 或 " - 如果 x 是 True,它返回 x 的值,否则它返回 y 的计算值。 | (a or b) 返回 10。 |
| not | not x | 布尔 " 非 " - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 | not(a and b) 返回 False |
5.4 赋值运算符
- 赋值运算符
=只做赋值,而不返回结果,与 C 语言的差别 - 海象运算符
:=赋值的同时,返回赋值的值
六、简单输入输出
Python 的 input() 和 print() 是最基础的 I/O 函数,详见 python-simple-io。
input()返回值永远是字符串(str),永不信任输入是必须遵守的规则print()的关键参数:sep(分隔符)、end(结尾字符)、file(输出目标)、flush(强制刷新)
基本数据结构
一、数字类型
- Python3 支持 int、float、bool、complex(复数)
- 数字类型是不可变数据
- 内置的
type()函数可以用来查询变量所指的对象类型
>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a).__namea__, type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
- 还可以用
isinstance来判断
>>> a = 111
>>> isinstance(a, int)
True
isinstance和type的区别在于:type()不会认为子类是一种父类类型。isinstance()会认为子类是一种父类类型。
- Python3 中,
bool是int的子类,True和False可以和数字相加,True+0、False+1会返回True,但可以通过is来判断类型。
二、字符串
Python 中的字符串用单引号 ' 或双引号 " 括起来,同时使用反斜杠 \ 转义特殊字符。
切片用于从序列中提取子序列。详见 python-slice-usage。
2.2 字符串是不可变数据
2.3 字符串的格式化输出
- % 格式化(C 风格,Python 1.x 时代)
name = "Kimi"
age = 3
# 基础用法
print("Hello, %s" % name) # Hello, Kimi
print("Age: %d, Pi: %.2f" % (age, 3.14159)) # Age: 3, Pi: 3.14
# 字典形式(解决多个参数混乱)
print("%(name)s is %(age)d years old" % {"name": name, "age": age})
- str.format()(Python 2.6+,3.0+ 主推)
name = "Kimi"
age = 3
# 位置参数
print("Hello, {}".format(name))
# 命名参数(可读性提升)
print("{name} is {age} years old".format(name=name, age=age))
# 格式控制
print("Pi = {:.2f}".format(3.14159)) # Pi = 3.14
print("Binary: {:b}".format(42)) # Binary: 101010
print("Centered: {:^10}".format("hi")) # Centered: hi
# 千位分隔 + 对齐
print("{:>10,}".format(1234567)) # ' 1,234,567'
# 解包字典
data = {"name": "Kimi", "age": 3}
print("{name} is {age} years old".format(**data))
- f-string(格式化字符串字面值,Python 3.6+) 现代首选
name = "Kimi"
age = 3
print(f"Hello, {name}!")
print(f"Next year I'll be {age + 1}")
f-string 的格式控制符非常丰富,包括对齐、填充、精度、进制转换等,详见 python-fstring-format-spec。
2.4 数据类型转换
- 隐式类型转换 - 自动完成
- 显式类型转换 - 需要使用类型函数来转换
数据类型的"高低"本质
- 精度 = 信息量,隐式转换时的保护机制:低转高是安全的(自动),高转低可能丢失信息(需显式)。
bool < int < float < complex- 类型高低是精度的层级的高低,转换可行是信息的映射的可行
| 方向 | 条件 | 结果 |
|---|---|---|
| 低 → 高 | 自动 | 安全,无损失 |
| 高 → 低 / 跨类型 | 需显式 | 取决于数据本身是否承载目标类型的信息 |
控制流
一、if 语句
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
if ... elif ... elif ... 序列可以当作其它语言中 switch 或 case 语句的替代品。
二、for 语句
Python 的 for 语句在列表或字符串等任意序列的元素上迭代,按它们在序列中出现的顺序,而不是像 C 或 Pascal 那样基于算术递增。
for Statements
- Python 不局限于在循环条件中仅作循环值的增减,而是直接可以传递迭代的序列内容
# Measure some strings:
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
- Python 中修改序列更简单的方式是通过迭代副本
# Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}
# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status
三、break 和 continue 语句
break语句将跳出最近的一层for或while循环continue语句将继续跳过循环的这一次迭代- 循环的
else子句:用于兜底,有点像switch语句的default兜底 在for或while循环中break语句可能对应一个else子句。 如果循环在未执行break的情况下结束,else子句将会执行 pass语句:即占位符,不执行任何动作
四、match 语句
模式匹配不是简单的 switch-case,而是"带形状验证的解构赋值"。属于高级应用,这里不做介绍。
其他补充点
一、布尔值与真值判断
1.1 空容器的布尔值
所有空容器在布尔上下文中都视为 False:
| 空容器 | bool() 结果 | 示例 |
|---|---|---|
空列表 [] | False | bool([]) → False |
空元组 () | False | bool(()) → False |
空字典 {} | False | bool({}) → False |
空集合 set() | False | bool(set()) → False |
空字符串 "" | False | bool("") → False |
空字节串 b"" | False | bool(b"") → False |
实用技巧(Pythonic 写法):
items = []
if not items: # ✅ 推荐,检查是否为空
print("列表为空")
if len(items) == 0: # ❌ 冗余,不推荐
print("列表为空")
1.2 数值的布尔值
| 数值 | bool() 结果 | 说明 |
|---|---|---|
0, 0.0 | False | 零值为假 |
| 非零整数 | True | 如 1, -1, 42 |
| 非零浮点数 | True | 如 0.1, -3.14 |
NaN (float) | True | 非零,所以为 True |
inf, -inf | True | 无穷大非零 |
二、逻辑运算符详解
2.1 核心规则(与 C 语言的关键区别)
| 运算符 | 返回规则 | 示例 | 结果 | 类型 |
|---|---|---|---|---|
and | 遇假即停,返回该假值;全真返最后一个 | 3 and 5 | 5 | int |
or | 遇真即停,返回该真值;全假返最后一个 | 0 or "hi" | "hi" | str |
not | 唯一强制返回 bool | not 3 | False | bool |
2.2 短路求值
# and 短路:左侧为假,右侧不执行
0 and expensive_func() # 返回 0,函数不执行
# or 短路:左侧为真,右侧不执行
3 or expensive_func() # 返回 3,函数不执行
2.3 优先级(从高到低)
not > and > or
陷阱示例:
not 3 and 0 # (not 3) and 0 → False and 0 → False
not (3 and 0) # not (3 and 0) → not 0 → True
3 and not 0 # 3 and (not 0) → 3 and True → True
2.4 实用技巧
# 设置默认值
name = user_input or "匿名" # 如果 user_input 为空字符串,返回 "匿名"
# 安全取值(链式判断)
user and user.is_admin and delete_data() # 只有全部满足才执行
三、f-string 格式化输出
格式控制符(对齐、填充、精度、进制转换等)的完整参考,详见 python-fstring-format-spec。
3.1 基础用法
name = "Kimi"
age = 3
print(f"Hello, {name}! You are {age} years old.")
3.2 调试神器(Python 3.8+)
x = 10
y = 20
print(f"{x=}, {y=}") # x=10, y=20
print(f"{x + y = }") # x + y = 30
四、命名规范(PEP 8)
4.1 核心命名风格
| 类型 | 规范 | 示例 | 反例 |
|---|---|---|---|
| 变量 | 蛇形命名法 | user_name | userName |
| 函数/方法 | 蛇形命名法 | get_value() | getValue() |
| 类 | 驼峰命名法 | UserInfo | user_info |
| 模块/文件 | 小写 + 下划线 | data_processor.py | DataProcessor.py |
| 常量 | 全大写 + 下划线 | MAX_SIZE | max_size |
| 私有变量 | 单下划线前缀 | _internal_cache | protected |
| 强私有变量 | 双下划线前缀 | __password | private |
| 魔术方法 | 双下划线前后缀 | __init__ | magic |
4.2 蛇形命名法(Snake Case)
# 正确
user_name = "Kimi"
file_path = "/home/user"
total_count = 100
http_request_handler = None
# 错误(这是 JavaScript/Java 风格)
userName = "Kimi"
filePath = "/home/user"
4.3 绝对避免
# 严重错误:覆盖内置函数
list = [1, 2, 3] # 无法再使用 list() 构造器
str = "hello" # 无法再用 str() 转换
# 改用
user_list = [1, 2, 3]
user_str = "hello"
五、三元表达式(条件表达式)
5.1 基础语法
value_if_true if condition else value_if_false
age = 20
status = "已成年" if age >= 18 else "未成年"
print(status)
5.2 与 if-elif 的区别
-
三元表达式:仅支持二分支(if-else)
-
if-elif:支持多分支(≥3 种情况)
# 二选一用三元
result = a if x else b
# 多分支用 if-elif(不要用嵌套三元!)
if age >= 18:
print("成年")
elif age >= 12:
print("青年")
else:
print("儿童")
六、练习题解析
6.1 练习题
| 题号 | 表达式 | 结果 | 类型 |
|---|---|---|---|
| 1 | True and False | False | bool |
| 2 | 10 or 20 | 10 | int |
| 3 | not 5 > 3 | False | bool |
| 4 | 0 and 100 | 0 | int |
| 5 | "" or "Python" | "Python" | str |
| 6 | True or True and False | True | bool |
| 7 | not (True or False) | False | bool |
| 8 | 5 > 3 and 2 < 1 | False | bool |
| 9 | [] and [1, 2] | [] | list |
| 10 | not 0 | True | bool |
| 11 | 1 and 2 and 3 | 3 | int |
| 12 | False or 0 | 0 | int |
| 13 | not "hello" | False | bool |
| 14 | 10 < 5 or 3 == 3 | True | bool |
| 15 | None or 1 | 1 | int |
| 16 | not None | True | bool |
| 17 | True and not False | True | bool |
| 18 | 0 or False or 10 | 10 | int |
| 19 | not 1 and 0 | False | bool |
| 20 | 2 > 1 and 5 < 3 or 4 == 4 | True | bool |
6.2 易错点总结
# 陷阱1:not 优先级高于比较?不,比较 > not
not 5 > 3 # not (5 > 3) = not True = False
# 陷阱2:and/or 返回原对象,不是 bool
3 and 5 # 5(不是 True)
False or 0 # 0(不是 False)
# 陷阱3:全为真时 and 返回最后一个
1 and 2 and 3 # 3(int,不是 True)
# 陷阱4:优先级 not > and > or
not 1 and 0 # (not 1) and 0 = False and 0 = False(不是 0!)
七、重点对比:Python vs C 语言
| 特性 | C 语言 | Python |
|---|---|---|
| 逻辑运算结果 | 强制 0 或 1(int) | 返回原对象(任意类型) |
3 && 5 | 1 | 5(int) |
3 | 0 | 1 | 3(int) |
!3 | 0 | False(bool) |
0 && func() | 0,func() 不执行 | 0,func() 不执行(短路一致) |
| 空指针/空值判断 | NULL == 0 | "", [], {}, None 等为假 |
Python 逻辑运算返回的是"东西",不是"真假标志",只有 not 是例外。