🐍 Python 基础语法讲解
一、Python 保留关键字
保留关键字是 Python 语言中已经被系统预先定义的标识符,不能作为变量名使用。
类别 | 关键字 | 含义 | 示例 |
逻辑值 | True False | 布尔值 | is_sunny = True |
空值 | None | 空,表示没有值 | result = None |
逻辑运算 | and or not | 与、或、非 | if a > 0 and b > 0: |
条件控制 | if elif else | 条件分支 | 见下节“条件控制” |
循环控制 | for while break continue | 循环语句 | 见下节“循环语句” |
异常处理 | try except finally raise | 异常捕获与抛出 | try: x=1/0 except: print("错误") |
函数 | def return lambda | 定义函数 / 返回值 / 匿名函数 | def add(x,y): return x+y |
类与对象 | class del | 类定义 / 删除对象引用 | class Person: |
模块导入 | import from as | 导入模块或函数 | import math , from math import sqrt |
作用域 | global nonlocal | 声明变量作用域 | global count |
异步 | async await | 异步操作(进阶内容) | 用于协程函数,暂不深入 |
其他 | assert pass in is with yield | 断言 / 占位 / 成员 / 对象 / 上下文 / 生成器 | assert x > 0 , pass |
二、标准数据类型
Python 的基本数据类型分为以下几类:
类型 | 名称 | 示例 |
数值型 | int , float , bool , complex | x = 10 , y = 3.14 , z = True |
字符串 | str | "Hello" 或 'World' |
列表 | list | [1, 2, "Python"] |
元组 | tuple | (1, 2, 3) |
集合 | set | {1, 2, 3} |
字典 | dict | {"name": "Tom", "age": 18} |
- 不可变:int、float、str、tuple
- 可变:list、dict、set
三、字符串(str
)
# 创建字符串
s1 = "Hello"
s2 = 'World'
# 字符串拼接与重复
s3 = s1 + " " + s2 # Hello World
s4 = s1 * 3 # HelloHelloHello
# 截取(切片)
print(s3[0:5]) # Hello
print(s3[-5:]) # World
# 字符串常用方法
print(s3.upper()) # 转大写
print(s3.lower()) # 转小写
print("lo" in s1) # True
四、列表(list
)
nums = [10, 20, 30, 40]
# 访问元素
print(nums[1]) # 20
# 切片
print(nums[1:3]) # [20, 30]
print(nums[::-1]) # [40, 30, 20, 10]
# 修改元素
nums[0] = 99
# 添加、删除
nums.append(50)
nums.remove(30)
五、元组(tuple
)
元组与列表相似,但一旦创建不能修改。
info = ("Tom", 18)
# 单元素元组必须加逗号
single = (42,)
print(type(single)) # <class 'tuple'>
# 访问
print(info[0]) # Tom
六、集合(set
)
集合不允许重复元素,常用于去重和集合运算。
s = {1, 2, 3, 3, 2}
print(s) # {1, 2, 3}
s.add(4)
s.remove(1)
# 交并差
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # 并集 {1,2,3,4,5}
print(a & b) # 交集 {3}
七、字典(dict
)
字典是键值对集合,键必须唯一且不可变。
student = {"name": "Tom", "age": 18}
# 访问键值
print(student["name"]) # Tom
# 修改、添加
student["age"] = 20
student["grade"] = "A"
# 遍历
for key, value in student.items():
print(key, value)
八、条件控制
score = 85
if score >= 90:
print("优秀")
elif score >= 60:
print("及格")
else:
print("不及格")
🔹 Python 使用 缩进 来标识语句块;缩进统一使用 4 个空格
九、循环语句
while 循环
n = 5
while n > 0:
print(n)
n -= 1
for 循环
for i in range(1, 6):
print(i)
# 遍历字符串
for c in "Python":
print(c)
break / continue
for i in range(5):
if i == 2:
continue # 跳过 2
print(i)
十、函数定义
# 定义函数
def greet(name):
return "Hello " + name
print(greet("Alice"))
lambda(匿名函数)
add = lambda x, y: x + y
print(add(3, 4)) # 7