跳到主要内容

基础语法

Python 以简洁可读著称。本篇梳理最常用的语法要点,帮助快速建立基础认知。

变量与动态类型

Python 是动态强类型语言,变量无需声明类型,类型由对象决定。

x = 10 # int
x = "hello" # str,合法
y: int = 20 # 标注类型,仅提示,不做强制检查

字符串与常用方法

字符串不可变。常用方法包括 splitjoinstripreplacestartswith

s = " hello,world "
s.strip().split(",") # ['hello', 'world']
",".join(["a", "b"]) # 'a,b'

容器:列表、元组、字典、集合

  • list:有序可变,适合频繁增删
  • tuple:有序不可变,可作为字典键
  • dict:键值映射,查找 O(1)
  • set:无序去重,成员测试 O(1)

控制流

if/elif/elseforwhile 配合 breakcontinue 使用,没有 switchmatch(3.10+)可替代。

for i, v in enumerate(["a", "b", "c"]):
if v == "b":
continue
print(i, v)

列表推导式

用一行表达式生成列表,比 append 循环更直观。

squares = [n * n for n in range(10) if n % 2 == 0]
# [0, 4, 16, 36, 64]

f-string 格式化

Python 3.6+ 推荐的字符串格式化方式,可嵌入表达式,3.12+ 支持嵌套引号与语句。

name = "Tom"
f"hello, {name.upper()}! 1+1={1+1}"
# 'hello, TOM! 1+1=2'