Skip to content

Python 基础语法

适合系统补齐 Python 基础知识。内容覆盖语法、数据结构、控制流、函数、面向对象与文件操作等高频主题。

基础语法

环境与基础

运行方式

python
## 方式1: 交互式 REPL
python  ## 进入交互模式

## 方式2: 脚本文件
python script.py

## 方式3: 直接执行(需要文件开头添加 shebang)
#!/usr/bin/env python3

注释

python
## 单行注释

"""
多行注释
可以用三引号
"""

'''
也可以用单引号
'''

变量与数据类型

变量声明

python
## Python 是动态类型,无需声明类型
name = "张三"
age = 25
is_active = True

## 多变量赋值
x, y, z = 1, 2, 3
a = b = c = 0

对比 JS/TS: Python 不需要 let/const/var,也不需要分号结尾

基本数据类型

数字类型
python
## 整数 int
x = 10
y = -5
big_num = 1_000_000  ## 可用下划线分隔

## 浮点数 float
pi = 3.14
e = 2.718

## 复数 complex
z = 3 + 4j

## 类型转换
int("123")      ## 123
float("3.14")   ## 3.14
str(123)        ## "123"
布尔类型
python
## bool 类型,首字母大写
is_valid = True
is_empty = False

## 假值(Falsy):False, None, 0, 0.0, '', [], {}, ()
## 其他都是真值

bool(0)      ## False
bool("")     ## False
bool([])     ## False
bool("0")    ## True (非空字符串)

注意: Python 用 True/False,不是 true/false

None 类型
python
## None 相当于 JS 的 null
result = None

## 检查 None
if result is None:
    print("结果为空")

## 不要用 ==,用 is
if result is not None:
    print("有结果")

字符串

基本操作
python
## 字符串定义
s1 = '单引号'
s2 = "双引号"
s3 = """多行
字符串"""

## 原始字符串(不转义)
path = r"C:\new\test"  ## 相当于 JS 的 String.raw

## f-string(推荐,相当于 JS 模板字符串)
name = "Alice"
age = 25
msg = f"我是 {name},今年 {age} 岁"
result = f"计算结果: {10 + 20}"

## 旧式格式化(了解即可)
"我是 %s" % name
"我是 {0},今年 {1} 岁".format(name, age)
字符串方法
python
s = "Hello World"

## 常用方法
s.upper()           ## "HELLO WORLD"
s.lower()           ## "hello world"
s.strip()           ## 去除首尾空白
s.replace("H", "J") ## "Jello World"
s.split(" ")        ## ["Hello", "World"]
s.startswith("He")  ## True
s.endswith("ld")    ## True
s.find("Wo")        ## 6 (索引位置,-1 表示未找到)
s.index("Wo")       ## 6 (未找到会抛异常)

## 字符串拼接
"Hello" + " " + "World"
" ".join(["Hello", "World"])  ## 推荐

## 字符串切片(重要!)
s = "Python"
s[0]      ## "P"
s[-1]     ## "n" (倒数第一个)
s[0:3]    ## "Pyt" (不含索引3)
s[2:]     ## "thon"
s[:4]     ## "Pyth"
s[::2]    ## "Pto" (步长为2)
s[::-1]   ## "nohtyP" (反转)

对比 JS: Python 字符串不可变,没有 charAt(),直接用索引访问

类型检查

python
type(123)           ## <class 'int'>
type("hello")       ## <class 'str'>
isinstance(123, int)  ## True (推荐)

## 查看对象所有属性和方法
dir(obj)
help(obj)

运算符

算术运算符

python
10 + 3   ## 13
10 - 3   ## 7
10 * 3   ## 30
10 / 3   ## 3.333... (浮点除法)
10 // 3  ## 3 (整除)
10 % 3   ## 1 (取模)
10 ** 3  ## 1000 (幂运算)

## 复合赋值
x += 1   ## x = x + 1
x *= 2   ## x = x * 2

注意: Python 有 // 整除和 ** 幂运算,JS 没有

比较运算符

python
==   ## 相等
!=   ## 不等
>    ## 大于
<    ## 小于
>=   ## 大于等于
<=   ## 小于等于

## 链式比较(Python 特色)
1 < x < 10  ## 相当于 1 < x and x < 10

逻辑运算符

python
and  ## 与 (相当于 JS 的 &&)
or   ## 或 (相当于 JS 的 ||)
not  ## 非 (相当于 JS 的 !)

## 示例
x > 0 and x < 10
not is_empty
result = value or default  ## 短路求值

身份运算符

python
is      ## 是否同一对象
is not  ## 是否不同对象

## 用于 None 检查
if x is None:
    pass

## 注意: is 检查对象身份,== 检查值相等
a = [1, 2]
b = [1, 2]
a == b  ## True (值相等)
a is b  ## False (不同对象)

成员运算符

python
in      ## 是否在序列中
not in  ## 是否不在序列中

## 示例
"a" in "abc"      ## True
1 in [1, 2, 3]    ## True
"name" in {"name": "Alice"}  ## True (字典检查键)

数据结构

列表 (List)

相当于 JS 的数组,但功能更强大
python
## 创建列表
nums = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
empty = []
matrix = [[1, 2], [3, 4]]  ## 二维列表

## 访问元素
nums[0]      ## 1
nums[-1]     ## 5 (倒数第一个)
nums[1:3]    ## [2, 3] (切片)

## 常用方法
nums.append(6)        ## 末尾添加
nums.insert(0, 0)     ## 指定位置插入
nums.extend([7, 8])   ## 合并列表
nums.remove(3)        ## 删除第一个3
nums.pop()            ## 删除并返回最后一个
nums.pop(0)           ## 删除并返回指定索引
nums.clear()          ## 清空
nums.index(3)         ## 查找索引
nums.count(3)         ## 统计出现次数
nums.sort()           ## 原地排序
nums.reverse()        ## 原地反转

## 列表推导式(重要!)
squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
matrix = [[i*j for j in range(3)] for i in range(3)]

## 其他操作
len(nums)            ## 长度
sum(nums)            ## 求和
max(nums), min(nums) ## 最大最小值
sorted(nums)         ## 返回新的排序列表
list(reversed(nums)) ## 反转(返回新列表)

## 列表拼接
[1, 2] + [3, 4]      ## [1, 2, 3, 4]
[1, 2] * 3           ## [1, 2, 1, 2, 1, 2]

元组 (Tuple)

不可变的列表,相当于只读数组
python
## 创建元组
coords = (10, 20)
single = (1,)        ## 单元素元组需要逗号
empty = ()

## 元组解包
x, y = coords        ## x=10, y=20
a, *rest, b = [1, 2, 3, 4, 5]  ## a=1, rest=[2,3,4], b=5

## 元组常用于函数返回多值
def get_user():
    return "Alice", 25, "alice@example.com"

name, age, email = get_user()

使用场景: 函数返回多值、字典的键、不可变数据

字典 (Dict)

相当于 JS 的对象/Map
python
## 创建字典
user = {
    "name": "Alice",
    "age": 25,
    "email": "alice@example.com"
}

## 空字典
empty = {}
empty = dict()

## 访问元素
user["name"]              ## "Alice"
user.get("name")          ## "Alice"
user.get("phone", "无")   ## 提供默认值,不存在返回"无"

## 修改/添加
user["age"] = 26
user["phone"] = "123456"

## 删除
del user["email"]
user.pop("age")          ## 删除并返回值

## 常用方法
user.keys()              ## 所有键
user.values()            ## 所有值
user.items()             ## 键值对
user.update({"city": "Beijing"})  ## 合并字典

## 检查键是否存在
if "name" in user:
    print(user["name"])

## 字典推导式
squares = {x: x**2 for x in range(5)}
## {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

## 遍历字典
for key in user:
    print(key, user[key])

for key, value in user.items():
    print(f"{key}: {value}")

集合 (Set)

无序、不重复的集合,相当于 JS 的 Set
python
## 创建集合
nums = {1, 2, 3, 4, 5}
empty = set()  ## 注意: {} 是空字典

## 集合操作
nums.add(6)              ## 添加元素
nums.remove(3)           ## 删除元素(不存在会报错)
nums.discard(3)          ## 删除元素(不存在不报错)
nums.clear()             ## 清空

## 集合运算
a = {1, 2, 3}
b = {3, 4, 5}

a | b    ## {1, 2, 3, 4, 5} 并集
a & b    ## {3} 交集
a - b    ## {1, 2} 差集
a ^ b    ## {1, 2, 4, 5} 对称差

## 集合推导式
squares = {x**2 for x in range(5)}

## 去重
unique_list = list(set([1, 2, 2, 3, 3, 3]))

控制流

if 语句

python
## 基本 if
if condition:
    ## 代码块用缩进表示(4个空格或1个Tab)
    print("条件为真")

## if-else
if x > 0:
    print("正数")
else:
    print("非正数")

## if-elif-else
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "D"

## 三元表达式
result = "偶数" if x % 2 == 0 else "奇数"

## 多条件
if x > 0 and x < 10:
    print("1到9之间")

if 0 < x < 10:  ## Python 特色:链式比较
    print("1到9之间")

重要: Python 用缩进表示代码块,不用花括号

for 循环

python
## 遍历列表
for item in [1, 2, 3]:
    print(item)

## 遍历字符串
for char in "Python":
    print(char)

## 遍历字典
user = {"name": "Alice", "age": 25}
for key in user:
    print(key, user[key])

for key, value in user.items():
    print(f"{key}: {value}")

## range() 函数(重要!)
for i in range(5):          ## 0,1,2,3,4
    print(i)

for i in range(1, 5):       ## 1,2,3,4
    print(i)

for i in range(0, 10, 2):   ## 0,2,4,6,8 (步长为2)
    print(i)

## enumerate() 获取索引和值
for index, value in enumerate(["a", "b", "c"]):
    print(f"{index}: {value}")

## zip() 并行遍历
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name}: {age}")

## else 子句(循环正常结束执行)
for i in range(5):
    if i == 3:
        break
else:
    print("循环正常结束")  ## break 不会执行这里

while 循环

python
## 基本 while
count = 0
while count < 5:
    print(count)
    count += 1

## while-else
while condition:
    ## 循环体
    pass
else:
    ## 循环正常结束执行
    pass

## 无限循环
while True:
    user_input = input("输入 'q' 退出: ")
    if user_input == 'q':
        break

break, continue, pass

python
## break: 跳出循环
for i in range(10):
    if i == 5:
        break
    print(i)  ## 0,1,2,3,4

## continue: 跳过当前迭代
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)  ## 1,3,5,7,9

## pass: 占位符,什么都不做
for i in range(5):
    pass  ## 空循环体

if condition:
    pass  ## 待实现

函数

函数定义

python
## 基本函数
def greet(name):
    return f"Hello, {name}!"

result = greet("Alice")

## 多返回值(返回元组)
def get_user():
    return "Alice", 25, "alice@example.com"

name, age, email = get_user()

## 默认参数
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

greet("Alice")              ## "Hello, Alice!"
greet("Alice", "Hi")        ## "Hi, Alice!"

## 关键字参数
def create_user(name, age, email):
    return {"name": name, "age": age, "email": email}

user = create_user(name="Alice", email="alice@example.com", age=25)

## 可变参数 *args (类似 JS 的 ...rest)
def sum_all(*numbers):
    return sum(numbers)

sum_all(1, 2, 3, 4, 5)  ## 15

## 关键字可变参数 **kwargs
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="Beijing")

## 混合使用
def func(a, b, *args, **kwargs):
    print(f"a={a}, b={b}")
    print(f"args={args}")
    print(f"kwargs={kwargs}")

func(1, 2, 3, 4, name="Alice", age=25)

Lambda 函数

python
## 匿名函数(单行表达式)
square = lambda x: x**2
add = lambda x, y: x + y

square(5)  ## 25
add(3, 4)  ## 7

## 常用于 map, filter, sorted
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))

## sorted 排序
users = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 20}
]
sorted_users = sorted(users, key=lambda u: u["age"])

作用域

python
## 全局变量
global_var = "全局"

def func():
    ## 局部变量
    local_var = "局部"
    print(global_var)  ## 可以访问全局变量
    
    ## 修改全局变量需要 global 关键字
    global global_var
    global_var = "修改后的全局"
    
    ## 嵌套函数
    def inner():
        nonlocal local_var  ## 访问外层函数变量
        local_var = "修改后的局部"
    
    inner()
    print(local_var)

函数文档

python
def calculate_area(radius):
    """
    计算圆的面积
    
    参数:
        radius (float): 圆的半径
    
    返回:
        float: 圆的面积
    """
    return 3.14 * radius ** 2

## 查看文档
help(calculate_area)
print(calculate_area.__doc__)

面向对象

类定义

python
## 基本类
class Person:
    ## 类属性(所有实例共享)
    species = "Human"
    
    ## 构造函数
    def __init__(self, name, age):
        ## 实例属性
        self.name = name
        self.age = age
    
    ## 实例方法
    def greet(self):
        return f"你好,我是 {self.name}"
    
    ## 类方法
    @classmethod
    def from_birth_year(cls, name, birth_year):
        age = 2026 - birth_year
        return cls(name, age)
    
    ## 静态方法
    @staticmethod
    def is_adult(age):
        return age >= 18
    
    ## 字符串表示
    def __str__(self):
        return f"Person(name={self.name}, age={self.age})"
    
    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

## 创建实例
alice = Person("Alice", 25)
print(alice.greet())

## 类方法调用
bob = Person.from_birth_year("Bob", 2000)

## 静态方法调用
Person.is_adult(20)  ## True

继承

python
## 单继承
class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)  ## 调用父类构造函数
        self.student_id = student_id
    
    ## 方法重写
    def greet(self):
        return f"你好,我是学生 {self.name}"
    
    ## 新方法
    def study(self, subject):
        return f"{self.name} 正在学习 {subject}"

student = Student("Charlie", 20, "S001")
print(student.greet())
print(student.study("Python"))

## 多继承
class Worker:
    def work(self):
        return "正在工作"

class StudentWorker(Student, Worker):
    pass

sw = StudentWorker("David", 22, "S002")
sw.study("Math")
sw.work()

属性装饰器

python
class Product:
    def __init__(self, price):
        self._price = price  ## 私有属性约定(单下划线)
    
    ## Getter
    @property
    def price(self):
        return self._price
    
    ## Setter
    @price.setter
    def price(self, value):
        if value < 0:
            raise ValueError("价格不能为负")
        self._price = value
    
    ## Deleter
    @price.deleter
    def price(self):
        del self._price

product = Product(100)
print(product.price)      ## 调用 getter
product.price = 200       ## 调用 setter
## del product.price       ## 调用 deleter

特殊方法(魔术方法)

python
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    ## 加法
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    ## 字符串表示
    def __str__(self):
        return f"Vector({self.x}, {self.y})"
    
    ## 长度
    def __len__(self):
        return int((self.x**2 + self.y**2)**0.5)
    
    ## 相等比较
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y
    
    ## 索引访问
    def __getitem__(self, index):
        if index == 0:
            return self.x
        elif index == 1:
            return self.y
        raise IndexError("索引超出范围")

v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2  ## 调用 __add__
print(v3)     ## 调用 __str__
print(v3[0])  ## 调用 __getitem__

异常处理

基本语法

python
## try-except
try:
    result = 10 / 0
except ZeroDivisionError:
    print("除数不能为零")

## 捕获多个异常
try:
    ## 可能出错的代码
    pass
except (ValueError, TypeError) as e:
    print(f"错误: {e}")

## 捕获所有异常
try:
    ## 代码
    pass
except Exception as e:
    print(f"发生错误: {e}")

## try-except-else-finally
try:
    result = 10 / 2
except ZeroDivisionError:
    print("除数不能为零")
else:
    print(f"结果是 {result}")  ## 没有异常时执行
finally:
    print("总是执行")  ## 无论是否异常都执行

抛出异常

python
## raise 抛出异常
def divide(a, b):
    if b == 0:
        raise ValueError("除数不能为零")
    return a / b

## 自定义异常
class CustomError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

raise CustomError("自定义错误消息")

## 重新抛出异常
try:
    ## 代码
    pass
except Exception as e:
    print(f"记录错误: {e}")
    raise  ## 重新抛出

常见异常类型

python
ValueError       ## 值错误
TypeError        ## 类型错误
KeyError         ## 字典键不存在
IndexError       ## 索引超出范围
FileNotFoundError  ## 文件不存在
ZeroDivisionError  ## 除零错误
AttributeError   ## 属性不存在
ImportError      ## 导入错误

文件操作

读写文件

python
## 写文件
with open("data.txt", "w", encoding="utf-8") as f:
    f.write("Hello World\n")
    f.write("第二行\n")

## 读文件(全部)
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

## 读文件(按行)
with open("data.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()  ## 返回列表
    for line in lines:
        print(line.strip())

## 逐行读取(内存高效)
with open("data.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

## 追加模式
with open("data.txt", "a", encoding="utf-8") as f:
    f.write("追加内容\n")

## 读写模式
with open("data.txt", "r+", encoding="utf-8") as f:
    content = f.read()
    f.write("新内容")

重要: 使用 with 语句自动关闭文件,相当于 JS 的 try-finally

文件模式

python
"r"   ## 只读(默认)
"w"   ## 写入(覆盖)
"a"   ## 追加
"x"   ## 独占创建(文件存在则失败)
"r+"  ## 读写
"w+"  ## 读写(覆盖)
"rb"  ## 二进制读
"wb"  ## 二进制写

JSON 操作

python
import json

## Python → JSON
data = {
    "name": "Alice",
    "age": 25,
    "hobbies": ["reading", "coding"]
}

## 写入 JSON 文件
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

## 转为 JSON 字符串
json_str = json.dumps(data, ensure_ascii=False, indent=2)

## JSON → Python
with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)

data = json.loads(json_str)

路径操作

python
import os
from pathlib import Path

## os 模块
os.getcwd()              ## 当前目录
os.listdir(".")          ## 列出目录内容
os.path.exists("file.txt")  ## 文件是否存在
os.path.isfile("file.txt")  ## 是否是文件
os.path.isdir("dir")     ## 是否是目录
os.path.join("dir", "file.txt")  ## 拼接路径
os.path.basename("/a/b/file.txt")  ## "file.txt"
os.path.dirname("/a/b/file.txt")   ## "/a/b"

## pathlib 模块(推荐)
path = Path("data.txt")
path.exists()            ## 是否存在
path.is_file()           ## 是否是文件
path.read_text()         ## 读取文本
path.write_text("内容")  ## 写入文本
path.parent              ## 父目录
path.name                ## 文件名
path.suffix              ## 扩展名

模块与包

导入模块

python
## 导入整个模块
import math
print(math.pi)

## 导入并重命名
import numpy as np

## 导入特定内容
from math import pi, sqrt
print(pi)

## 导入所有(不推荐)
from math import *

## 导入自定义模块
## 文件 utils.py
def add(a, b):
    return a + b

## 另一个文件
from utils import add

常用内置模块

python
## math - 数学函数
import math
math.sqrt(16)    ## 4.0
math.ceil(3.2)   ## 4
math.floor(3.8)  ## 3
math.pi          ## 3.141592653589793

## random - 随机数
import random
random.random()           ## 0.0-1.0 随机浮点数
random.randint(1, 10)     ## 1-10 随机整数
random.choice([1, 2, 3])  ## 随机选择
random.shuffle(list)      ## 打乱列表

## datetime - 日期时间
from datetime import datetime, date, timedelta

now = datetime.now()
today = date.today()
tomorrow = today + timedelta(days=1)

## 格式化
now.strftime("%Y-%m-%d %H:%M:%S")
## 解析
datetime.strptime("2026-01-29", "%Y-%m-%d")

## time - 时间
import time
time.time()        ## 时间戳
time.sleep(1)      ## 暂停1秒

## os - 操作系统
import os
os.environ["PATH"]  ## 环境变量

## sys - 系统
import sys
sys.version        ## Python 版本
sys.argv           ## 命令行参数
sys.exit()         ## 退出程序

## re - 正则表达式
import re
re.match(r"^\d+$", "123")   ## 匹配
re.search(r"\d+", "abc123") ## 搜索
re.findall(r"\d+", "a1b2c3") ## 查找所有
re.sub(r"\d+", "X", "a1b2")  ## 替换

第三方包管理

bash
## pip 安装包
pip install requests
pip install pandas numpy matplotlib

## 安装指定版本
pip install requests==2.28.0

## 卸载
pip uninstall requests

## 列出已安装
pip list

## 导出依赖
pip freeze > requirements.txt

## 安装依赖
pip install -r requirements.txt

高级特性

列表推导式

python
## 基本形式
squares = [x**2 for x in range(10)]

## 带条件
evens = [x for x in range(10) if x % 2 == 0]

## 多重循环
pairs = [(x, y) for x in range(3) for y in range(3)]

## 嵌套
matrix = [[i*j for j in range(3)] for i in range(3)]

生成器

python
## 生成器表达式(不占内存)
squares_gen = (x**2 for x in range(1000000))

## 生成器函数
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)

装饰器

python
## 函数装饰器
def log(func):
    def wrapper(*args, **kwargs):
        print(f"调用 {func.__name__}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} 返回 {result}")
        return result
    return wrapper

@log
def add(a, b):
    return a + b

add(1, 2)  ## 会打印日志

## 带参数的装饰器
def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def greet():
    print("Hello")

greet()  ## 打印3次

上下文管理器

python
## with 语句
with open("file.txt") as f:
    content = f.read()
## 文件自动关闭

## 自定义上下文管理器
class MyContext:
    def __enter__(self):
        print("进入")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("退出")

with MyContext() as ctx:
    print("执行中")

## 使用 contextlib
from contextlib import contextmanager

@contextmanager
def my_context():
    print("进入")
    yield
    print("退出")

with my_context():
    print("执行中")

迭代器

python
## 可迭代对象
for item in [1, 2, 3]:  ## 列表是可迭代的
    print(item)

## 迭代器
it = iter([1, 2, 3])
print(next(it))  ## 1
print(next(it))  ## 2

## 自定义迭代器
class Counter:
    def __init__(self, max):
        self.max = max
        self.current = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.current >= self.max:
            raise StopIteration
        self.current += 1
        return self.current

for num in Counter(5):
    print(num)

与 JavaScript/Java 对比

语法差异

特性PythonJavaScriptJava
变量声明直接赋值let/const/var类型 变量名
代码块缩进花括号花括号
注释##////
字符串拼接f"{a}{b}"${a}${b}a + b
布尔值True/Falsetrue/falsetrue/false
空值Nonenull/undefinednull
数组/列表[1,2,3][1,2,3]new int[]
字典/对象Map<K,V>
函数定义def func():function func(){}type func(){}
类定义class C:class C {}class C {}
继承class B(A):class B extends Aclass B extends A

命名规范

python
## Python (PEP 8)
variable_name        ## 变量/函数: snake_case
ClassName            ## 类: PascalCase
CONSTANT_NAME        ## 常量: UPPER_CASE
_private_var         ## 私有变量: 前缀 _
__very_private       ## 强私有: 前缀 __

## JavaScript
variableName         ## 变量/函数: camelCase
ClassName            ## 类: PascalCase
CONSTANT_NAME        ## 常量: UPPER_CASE

## Java
variableName         ## 变量/方法: camelCase
ClassName            ## 类: PascalCase
CONSTANT_NAME        ## 常量: UPPER_CASE

实战技巧

常用代码片段

python
## 交换变量
a, b = b, a

## 多变量赋值
x = y = z = 0

## 链式比较
if 0 < x < 10:
    pass

## 三元表达式
result = "偶数" if x % 2 == 0 else "奇数"

## 字符串反转
s[::-1]

## 列表去重
list(set([1, 2, 2, 3]))

## 字典合并
d1 = {"a": 1}
d2 = {"b": 2}
{**d1, **d2}  ## {"a": 1, "b": 2}

## 默认值
result = value or default

## 条件表达式
if x in [1, 2, 3]:
    pass

调试技巧

python
## 打印调试
print(f"x = {x}")

## 查看类型
type(obj)

## 查看属性和方法
dir(obj)

## 查看文档
help(function)

## 断言
assert x > 0, "x 必须大于 0"

## pdb 调试器
import pdb
pdb.set_trace()  ## 设置断点

性能优化

python
## 使用生成器代替列表(节省内存)
sum(x**2 for x in range(1000000))  ## 好
sum([x**2 for x in range(1000000)])  ## 差

## 使用 set 检查成员(O(1) vs O(n))
if item in my_set:  ## 好
if item in my_list:  ## 差

## 字符串拼接
"".join(strings)  ## 好
result = ""
for s in strings:
    result += s  ## 差

## 使用局部变量(更快)
def func():
    local_len = len  ## 缓存全局函数
    for item in items:
        if local_len(item) > 10:
            pass
最近更新