2025-04-10
编程
00

目录

1. 基本结构
2. 数据类型
3. 输入与输出
4. 控制结构
条件语句
循环
5. 函数
默认参数和关键字参数
6. 列表操作
7. 字典操作
8. 文件操作
9. 异常处理
10. 面向对象编程
定义类和对象
继承
11. 模块与包
12. 列表推导式
13. Lambda 表达式
14. 标准库
15. 装饰器
16. 迭代器与生成器
迭代器
生成器
17. 上下文管理器
18. 装饰器进阶
19. 并发编程
线程
进程
异步 I/O
20. 元类与反射
21. 正则表达式
22. 数据科学库
23. Web 开发框架

Python 是一种简洁、易读且功能强大的编程语言,广泛应用于 Web 开发、数据分析、人工智能、自动化脚本等领域。以下是 Python 的基础语法要点:

1. 基本结构

Python 程序不需要显式的入口点(如 main() 函数),代码从上到下逐行执行。

python
print("Hello, World!") # 输出内容到控制台

提示

python程序使用 # 作为注释符号


2. 数据类型

Python 支持多种内置数据类型:

  • 整型int
  • 浮点型float
  • 字符串str
  • 布尔型bool
  • 列表list
  • 元组tuple
  • 字典dict
  • 集合set
python
# 示例 age = 25 # int height = 5.7 # float name = "Alice" # str is_student = True # bool numbers = [1, 2, 3] # list coordinates = (4, 5) # tuple person = {"name": "Bob", "age": 30} # dict unique_numbers = {1, 2, 3, 3} # set

3. 输入与输出

使用 input() 获取用户输入,使用 print() 输出内容。

python
name = input("Enter your name: ") print(f"Hello, {name}!")

4. 控制结构

条件语句

python
if age >= 18: print("You are an adult.") elif age >= 13: print("You are a teenager.") else: print("You are a child.")

循环

  • for 循环:
python
for i in range(5): # 遍历 0 到 4 print(i)
  • while 循环:
python
count = 0 while count < 5: print(count) count += 1

5. 函数

使用 def 关键字定义函数。

python
def greet(name): return f"Hello, {name}!" message = greet("Alice") print(message) # 输出: Hello, Alice!

默认参数和关键字参数

python
def greet(name="Guest"): return f"Hello, {name}!" print(greet()) # 输出: Hello, Guest! print(greet("Alice")) # 输出: Hello, Alice!

6. 列表操作

列表是 Python 中最常用的数据结构之一。

  • 创建列表:
python
fruits = ["apple", "banana", "cherry"]
  • 添加元素:
python
fruits.append("orange") # 在末尾添加 fruits.insert(1, "grape") # 在索引 1 处插入
  • 删除元素:
python
fruits.remove("banana") # 删除指定值 del fruits[0] # 删除索引为 0 的元素
  • 遍历列表:
python
for fruit in fruits: print(fruit)

7. 字典操作

字典是以键值对形式存储数据的结构。

  • 创建字典:
python
person = {"name": "Alice", "age": 25}
  • 访问和修改:
python
print(person["name"]) # 输出: Alice person["age"] = 26 # 修改年龄
  • 遍历字典:
python
for key, value in person.items(): print(f"{key}: {value}")

8. 文件操作

Python 提供了简单的方式处理文件。

  • 打开文件并读取内容:
python
with open("example.txt", "r") as file: content = file.read() print(content)
  • 写入文件:
python
with open("example.txt", "w") as file: file.write("Hello, File!")

9. 异常处理

使用 try...except 捕获和处理异常。

python
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") finally: print("Execution complete.")

10. 面向对象编程

Python 支持面向对象编程(OOP),可以通过类和对象实现封装、继承和多态。

定义类和对象

python
class Person: def __init__(self, name, age): self.name = name self.age = age def introduce(self): print(f"My name is {self.name} and I am {self.age} years old.") # 创建对象 alice = Person("Alice", 25) alice.introduce() # 输出: My name is Alice and I am 25 years old.

继承

python
class Student(Person): def __init__(self, name, age, grade): super().__init__(name, age) self.grade = grade def study(self): print(f"{self.name} is studying in grade {self.grade}.") student = Student("Bob", 15, 10) student.introduce() # 输出: My name is Bob and I am 15 years old. student.study() # 输出: Bob is studying in grade 10.

11. 模块与包

模块是一个包含 Python 代码的文件,而包是包含多个模块的目录。

  • 导入模块:
python
import math print(math.sqrt(16)) # 输出: 4.0
  • 导入特定函数:
python
from math import sqrt print(sqrt(16)) # 输出: 4.0
  • 自定义模块: 假设有一个文件 mymodule.py
python
def greet(name): return f"Hello, {name}!"

在另一个文件中导入:

python
import mymodule print(mymodule.greet("Alice"))

12. 列表推导式

列表推导式是一种简洁的方式来创建列表。

python
squares = [x**2 for x in range(10)] print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

13. Lambda 表达式

Lambda 表达式用于定义匿名函数。

python
add = lambda x, y: x + y print(add(5, 3)) # 输出: 8

14. 标准库

Python 提供了许多标准库,用于处理各种任务:

  • os:操作系统接口。
  • datetime:日期和时间处理。
  • random:随机数生成。
  • json:JSON 数据处理。

示例:

python
import random print(random.randint(1, 10)) # 随机生成 1 到 10 的整数

15. 装饰器

装饰器用于修改函数或方法的行为。

python
def log_function(func): def wrapper(*args, **kwargs): print(f"Calling function {func.__name__}") return func(*args, **kwargs) return wrapper @log_function def greet(name): print(f"Hello, {name}!") greet("Alice") # 输出: # Calling function greet # Hello, Alice!

16. 迭代器与生成器

迭代器

迭代器是一个可以记住遍历位置的对象。它从集合的第一个元素开始访问,直到所有的元素被访问完结束。

  • 使用 iter()next() 方法:
python
my_list = [1, 2, 3] it = iter(my_list) print(next(it)) # 输出: 1 print(next(it)) # 输出: 2

生成器

生成器是一种特殊的迭代器,使用函数和 yield 语句来实现。

  • 定义生成器:
python
def my_generator(): yield 1 yield 2 yield 3 for value in my_generator(): print(value) # 输出: 1, 2, 3
  • 生成器表达式: 类似于列表推导式,但使用圆括号。
python
gen = (x**2 for x in range(5)) for num in gen: print(num) # 输出: 0, 1, 4, 9, 16

17. 上下文管理器

上下文管理器允许你在不需要手动管理资源的情况下执行代码块。最常用的例子是文件操作。

  • 使用 with 语句:
python
with open('example.txt', 'w') as file: file.write('Hello, World!') # 文件会自动关闭
  • 自定义上下文管理器: 通过实现 __enter____exit__ 方法来创建自定义上下文管理器。
python
class MyContextManager: def __enter__(self): print("Entering the context") return self def __exit__(self, exc_type, exc_val, exc_tb): print("Exiting the context") with MyContextManager() as manager: print("Inside the context") # 输出: # Entering the context # Inside the context # Exiting the context

18. 装饰器进阶

装饰器不仅可以用来记录日志,还可以用于缓存、权限验证等场景。

  • 带参数的装饰器:
python
def repeat(num_times): def decorator_repeat(func): def wrapper(*args, **kwargs): for _ in range(num_times): result = func(*args, **kwargs) return result return wrapper return decorator_repeat @repeat(num_times=3) def greet(name): print(f"Hello {name}") greet("Alice") # 输出: # Hello Alice # Hello Alice # Hello Alice

19. 并发编程

Python 提供了多种方式来进行并发编程,包括线程、进程和异步 I/O。

线程

  • 使用 threading 模块:
python
import threading import time def worker(): print(f"Thread {threading.current_thread().name} starting") time.sleep(2) print(f"Thread {threading.current_thread().name} finishing") threads = [] for i in range(3): thread = threading.Thread(target=worker) threads.append(thread) thread.start() for thread in threads: thread.join()

进程

  • 使用 multiprocessing 模块:
python
from multiprocessing import Process import os def info(title): print(title) print('module name:', __name__) print('parent process:', os.getppid()) print('process id:', os.getpid()) def f(name): info('function f') print('hello', name) if __name__ == '__main__': info('main line') p = Process(target=f, args=('bob',)) p.start() p.join()

异步 I/O

  • 使用 asyncio 模块:
python
import asyncio async def say_after(delay, what): await asyncio.sleep(delay) print(what) async def main(): task1 = asyncio.create_task(say_after(1, 'hello')) task2 = asyncio.create_task(say_after(2, 'world')) await task1 await task2 asyncio.run(main())

20. 元类与反射

元类是类的类,用于控制类的行为。反射则是在运行时检查或修改类结构的能力。

  • 定义元类:
python
class Meta(type): def __new__(cls, name, bases, dct): print("Creating class", name) return super().__new__(cls, name, bases, dct) class MyClass(metaclass=Meta): pass obj = MyClass()
  • 反射示例:
python
class Person: def __init__(self, name): self.name = name p = Person("Alice") print(getattr(p, "name")) # 输出: Alice setattr(p, "age", 25) print(hasattr(p, "age")) # 输出: True delattr(p, "age")

21. 正则表达式

Python 提供了 re 模块来处理正则表达式。

  • 基本用法:
python
import re pattern = r'\d+' text = "There are 123 apples and 456 oranges." matches = re.findall(pattern, text) print(matches) # 输出: ['123', '456']
  • 替换匹配内容:
python
result = re.sub(pattern, 'XXX', text) print(result) # 输出: There are XXX apples and XXX oranges.

22. 数据科学库

Python 在数据科学领域非常流行,主要得益于一些强大的第三方库,如 NumPy、Pandas、Matplotlib 和 Scikit-learn。

  • NumPy:用于数值计算。
python
import numpy as np arr = np.array([1, 2, 3]) print(arr * 2) # 输出: [2 4 6]
  • Pandas:用于数据分析。
python
import pandas as pd df = pd.DataFrame({ 'A': [1, 2, 3], 'B': [4, 5, 6] }) print(df.head()) # 输出前几行
  • Matplotlib:用于绘制图表。
python
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.show()

23. Web 开发框架

Python 有许多优秀的 Web 框架,如 Django 和 Flask。

  • Flask 示例:
python
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' if __name__ == "__main__": app.run()