Python 基本语法详解
Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名。以下是 Python 基本语法的详细介绍:
1. 注释
# 这是单行注释
"""
这是多行注释
可以用三个双引号
"""
'''
这也是多行注释
可以用三个单引号
'''
2. 变量与数据类型
Python 是动态类型语言,不需要声明变量类型。
# 基本数据类型
x = 10 # 整数 (int)
y = 3.14 # 浮点数 (float)
z = "Hello" # 字符串 (str)
is_true = True # 布尔值 (bool)
# 类型转换
int("123") # 字符串转整数
float("3.14") # 字符串转浮点数
str(123) # 数字转字符串
3. 运算符
# 算术运算符
a = 10 + 3 # 加
b = 10 - 3 # 减
c = 10 * 3 # 乘
d = 10 / 3 # 除 (结果为浮点数)
e = 10 // 3 # 整除 (结果为整数)
f = 10 % 3 # 取模
g = 10 ** 3 # 幂运算
# 比较运算符
10 == 10 # 等于
10 != 11 # 不等于
10 > 5 # 大于
10 < 20 # 小于
10 >= 10 # 大于等于
10 <= 20 # 小于等于
# 逻辑运算符
True and False # 与
True or False # 或
not True # 非
4. 字符串操作
s = "Python"
# 字符串索引和切片
s[0] # 'P' (第一个字符)
s[-1] # 'n' (最后一个字符)
s[1:4] # 'yth' (切片)
s[:3] # 'Pyt' (从开始到索引3)
s[3:] # 'hon' (从索引3到结束)
# 字符串方法
s.upper() # 'PYTHON' (转为大写)
s.lower() # 'python' (转为小写)
s.strip() # 去除两端空白
s.split('h') # ['Pyt', 'on'] (分割字符串)
len(s) # 6 (字符串长度)
5. 列表 (List)
my_list = [1, 2, 3, 'a', 'b', 'c']
# 列表操作
my_list[0] # 1 (索引访问)
my_list[-1] # 'c' (负索引)
my_list[1:4] # [2, 3, 'a'] (切片)
my_list.append('d') # 添加元素
my_list.remove(2) # 移除元素
len(my_list) # 获取长度
# 列表方法
[1, 2] + [3, 4] # [1, 2, 3, 4] (合并列表)
[1] * 3 # [1, 1, 1] (重复)
3 in [1, 2, 3] # True (成员检查)
6. 元组 (Tuple)
不可变的序列类型
my_tuple = (1, 2, 3, 'a', 'b')
# 元组操作
my_tuple[0] # 1 (索引访问)
my_tuple[1:3] # (2, 3) (切片)
len(my_tuple) # 获取长度
7. 字典 (Dictionary)
键值对集合
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 字典操作
my_dict['name'] # 'Alice' (访问值)
my_dict['age'] = 26 # 修改值
my_dict['job'] = 'Engineer' # 添加新键值对
'age' in my_dict # True (检查键是否存在)
# 字典方法
my_dict.keys() # 获取所有键
my_dict.values() # 获取所有值
my_dict.items() # 获取所有键值对
8. 集合 (Set)
无序不重复元素集
my_set = {1, 2, 3, 3, 4} # {1, 2, 3, 4} (自动去重)
# 集合操作
my_set.add(5) # 添加元素
my_set.remove(2) # 移除元素
len(my_set) # 获取长度
# 集合运算
{1, 2} | {2, 3} # {1, 2, 3} (并集)
{1, 2} & {2, 3} # {2} (交集)
{1, 2} - {2, 3} # {1} (差集)
9. 控制流
if 语句
x = 10
if x > 10:
print("大于10")
elif x == 10:
print("等于10")
else:
print("小于10")
for 循环
# 遍历列表
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# 使用range
for i in range(5): # 0到4
print(i)
for i in range(1, 6): # 1到5
print(i)
for i in range(0, 10, 2): # 0,2,4,6,8
print(i)
while 循环
count = 0
while count < 5:
print(count)
count += 1
循环控制
# break - 终止循环
for i in range(10):
if i == 5:
break
print(i)
# continue - 跳过当前迭代
for i in range(10):
if i % 2 == 0:
continue
print(i) # 只打印奇数
10. 函数
# 定义函数
def greet(name):
"""这是一个问候函数""" # 文档字符串
return f"Hello, {name}!"
# 调用函数
message = greet("Alice")
print(message)
# 默认参数
def power(base, exponent=2):
return base ** exponent
# 关键字参数
power(exponent=3, base=2) # 8
# 可变参数
def sum_all(*args):
return sum(args)
sum_all(1, 2, 3, 4) # 10
# 关键字可变参数
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25)
11. 异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零!")
except Exception as e:
print(f"发生错误: {e}")
else:
print("没有发生错误")
finally:
print("无论是否发生错误都会执行")
12. 文件操作
# 写入文件
with open('example.txt', 'w') as f:
f.write("Hello, World!")
# 读取文件
with open('example.txt', 'r') as f:
content = f.read()
print(content)
# 逐行读取
with open('example.txt', 'r') as f:
for line in f:
print(line.strip())
13. 面向对象编程
# 定义类
class Person:
# 类属性
species = "Homo sapiens"
# 初始化方法
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 实例方法
def greet(self):
return f"Hello, my name is {self.name}"
# 类方法
@classmethod
def get_species(cls):
return cls.species
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 创建实例
alice = Person("Alice", 25)
# 访问属性和方法
print(alice.name) # Alice
print(alice.greet()) # Hello, my name is Alice
print(Person.get_species()) # Homo sapiens
print(Person.is_adult(20)) # True
14. 模块和包
# 导入整个模块
import math
print(math.sqrt(16)) # 4.0
# 导入特定函数
from math import sqrt, pi
print(sqrt(9)) # 3.0
# 导入并重命名
import numpy as np
# 从包中导入模块
from package import module
# 创建自己的模块
# 创建一个.py文件,里面包含函数和变量,然后可以导入使用
15. 列表推导式
# 基本列表推导式
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]
# 字典推导式
square_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
16. 生成器
生成器是一种特殊的迭代器,可以按需生成值,而不是一次性生成所有值,从而节省内存。
生成器函数
def count_down(n):
print("Starting count down")
while n > 0:
yield n # 每次调用next()时执行到这里并返回n
n -= 1
print("Count down completed")
# 使用生成器
counter = count_down(3)
print(next(counter)) # 输出: Starting count down 然后 3
print(next(counter)) # 输出: 2
print(next(counter)) # 输出: 1
# print(next(counter)) # 会抛出StopIteration异常,并输出"Count down completed"
生成器表达式
# 类似于列表推导式,但使用圆括号
gen = (x**2 for x in range(1000000)) # 不会立即创建100万个数的列表
# 使用
for num in gen:
if num > 100:
break
print(num)
生成器的高级用法
send() 方法:可以向生成器发送值
def accumulator():
total = 0
while True:
value = yield total
if value is None:
break
total += value
acc = accumulator()
next(acc) # 启动生成器,返回0
print(acc.send(10)) # 返回10
print(acc.send(20)) # 返回30
yield from:委托给子生成器
def chain(*iterables):
for it in iterables:
yield from it
list(chain('ABC', 'DEF')) # ['A', 'B', 'C', 'D', 'E', 'F']
17. Lambda 函数
Lambda函数是匿名函数,用于创建小型的一次性函数。
基本语法
lambda arguments: expression
使用场景
简单函数操作:
square = lambda x: x**2
print(square(4)) # 16
作为参数传递:
# 排序
pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
pairs.sort(key=lambda pair: pair[1]) # 按第二个元素排序
# 过滤
numbers = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
# 映射
squares = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25]
限制
- 只能包含一个表达式
- 不能包含语句或注解
- 没有return语句(表达式结果自动返回)
- 不能包含循环或条件语句(但可以使用条件表达式)
18. 装饰器
装饰器是修改其他函数行为的函数,提供了一种简洁的语法来应用高阶函数。
基本装饰器
def simple_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@simple_decorator
def say_hello():
print("Hello!")
say_hello()
"""
输出:
Before function call
Hello!
After function call
"""
带参数的装饰器
def repeat(num_times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(num_times=3)
def greet(name):
print(f"Hello {name}")
greet("Alice")
"""
输出:
Hello Alice
Hello Alice
Hello Alice
"""
类装饰器
class CountCalls:
def __init__(self, func):
self.func = func
self.num_calls = 0
def __call__(self, *args, **kwargs):
self.num_calls += 1
print(f"Call {self.num_calls} of {self.func.__name__}")
return self.func(*args, **kwargs)
@CountCalls
def say_hello():
print("Hello!")
say_hello()
say_hello()
"""
输出:
Call 1 of say_hello
Hello!
Call 2 of say_hello
Hello!
"""
内置装饰器
# @property - 将方法转换为属性
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius must be positive")
self._radius = value
# @classmethod - 定义类方法
class MyClass:
@classmethod
def class_method(cls):
print(f"Called class method of {cls}")
# @staticmethod - 定义静态方法
class MyClass:
@staticmethod
def static_method():
print("Called static method")
19. 上下文管理器 (Context Managers)
用于管理资源,确保资源被正确释放。
# 使用with语句
with open('file.txt', 'r') as f:
content = f.read()
# 自定义上下文管理器
from contextlib import contextmanager
@contextmanager
def managed_resource(*args, **kwds):
# 初始化代码
resource = acquire_resource(*args, **kwds)
try:
yield resource
finally:
# 清理代码
release_resource(resource)
# 使用
with managed_resource(timeout=3600) as resource:
# 使用resource
pass
20. 协程 (Coroutines) 和 async/await
用于异步编程。
import asyncio
async def fetch_data():
print("Start fetching")
await asyncio.sleep(2) # 模拟IO操作
print("Done fetching")
return {'data': 1}
async def main():
task = asyncio.create_task(fetch_data())
print("Do other things")
data = await task
print(f"Received data: {data}")
asyncio.run(main())
21. 描述符 (Descriptors)
控制属性访问。
class PositiveNumber:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, type=None):
return obj.__dict__.get(self.name)
def __set__(self, obj, value):
if value <= 0:
raise ValueError("Value must be positive")
obj.__dict__[self.name] = value
class MyClass:
number = PositiveNumber()
obj = MyClass()
obj.number = 10 # 有效
# obj.number = -5 # 抛出ValueError
22. 元类 (Metaclasses)
控制类的创建。
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
pass
a = Singleton()
b = Singleton()
print(a is b) # True
23. 数据类 (Data Classes)
Python 3.7+ 引入,简化类的创建。
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
z: float = 0.0 # 默认值
p = Point(1.5, 2.5)
print(p) # Point(x=1.5, y=2.5, z=0.0)
24. 类型注解 (Type Hints)
Python 3.5+ 引入,提高代码可读性和IDE支持。
from typing import List, Dict, Optional, Union
def greet(name: str) -> str:
return f"Hello, {name}"
def process(items: List[Union[int, str]]) -> Dict[str, int]:
return {"count": len(items)}
class Node:
def __init__(self, value: int, next: Optional['Node'] = None):
self.value = value
self.next = next
25. 模式匹配 (Pattern Matching)
Python 3.10+ 引入。
def handle_command(command):
match command.split():
case ["quit"]:
print("Goodbye!")
return False
case ["look"]:
print("You see nothing special.")
case ["get", obj]:
print(f"You pick up the {obj}.")
case ["go", direction] if direction in ["north", "south"]:
print(f"You go {direction}.")
case ["go", _]:
print("You can't go that way.")
case _:
print("I don't understand that command.")
return True