Python 基础教程
下面是 Python 编程基础知识最系统、最清晰的导图式总结,非常适合自学、复习、打基础。
内容分为 8 大模块,从最基础到能写实际项目。
# 单行注释
"""
多行注释
"""
详细文档:变量
- int(整数)
- float(浮点数)
- bool(布尔)
- str(字符串)
- list(列表)
- dict(字典)
- datetime(日期时间)
- None(空)
详细文档:基本运算
- 算术:+ - * / // % **
- 比较:== != > < >= <=
- 逻辑:and or not
详细文档:列表
nums = [1, 2, 3]
nums.append(4)
详细文档:元组
t = (1, 2, 3)
s = {1, 2, 3}
person = {"name": "Tom", "age": 20}
if x > 0:
...
elif x == 0:
...
else:
...
for i in range(5):
...
while condition:
...
break / continue
函数定义
def add(a, b):
return a + b
默认参数
def greet(name="Tom"):
print("Hi", name)
可变参数
def f(*args, **kwargs):
...
导入模块
import math
from datetime import datetime
自己创建模块(文件 .py)
安装第三方库
pip install requests
类与对象
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name, "barks")
d = Dog("Coco")
d.bark()
继承
class A:
pass
class B(A):
pass
方法类型:
- 实例方法(self)
- 类方法(@classmethod)
- 静态方法(@staticmethod)
文件读取
with open("a.txt") as f:
text = f.read()
文件写入
with open("a.txt", "w") as f:
f.write("hello")
| 库 | 用途 |
|---|---|
| os | 文件系统 |
| sys | 解释器相关 |
| datetime | 日期时间 |
| json | JSON 解析 |
| math | 数学函数 |
| random | 随机数 |
| re | 正则表达式 |
try:
x = 1 / 0
except ZeroDivisionError:
print("division by zero")
finally:
print("done")
列表推导式
[x * 2 for x in range(5)]
生成器
def gen():
yield 1
yield 2
lambda
f = lambda x: x + 1
装饰器
def deco(fn):
def wrapper():
print("before")
fn()
return wrapper