一、Python简介

Python是解释型、面向对象、动态类型的高级编程语言。

特点:

  • 语法简洁易读
  • 丰富的标准库和第三方库
  • 跨平台
  • 支持多种编程范式

二、基础语法

变量和数据类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 数字
a = 10 # int
b = 3.14 # float
c = 1 + 2j # complex

# 字符串
s = "Hello"
s = 'World'
s = """多行
字符串"""

# 布尔
flag = True
flag = False

# None
value = None

# 类型转换
int("123") # 123
str(123) # "123"
float("3.14") # 3.14

运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 算术运算符
+ - * / // % **

# 比较运算符
== != > < >= <=

# 逻辑运算符
and or not

# 成员运算符
in not in

# 身份运算符
is is not

字符串操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
s = "Hello World"

# 索引和切片
s[0] # 'H'
s[-1] # 'd'
s[0:5] # 'Hello'
s[6:] # 'World'
s[::-1] # 'dlroW olleH'

# 常用方法
s.lower() # 'hello world'
s.upper() # 'HELLO WORLD'
s.split() # ['Hello', 'World']
'-'.join(['a','b']) # 'a-b'
s.replace('World', 'Python')
s.startswith('Hello')
s.endswith('World')
'Hello' in s # True
len(s) # 11

# 格式化
name = "张三"
age = 20
f"姓名:{name}, 年龄:{age}"
"姓名:{}, 年龄:{}".format(name, age)
"姓名:%s, 年龄:%d" % (name, age)

三、数据结构

列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 创建
lst = [1, 2, 3, 4, 5]
lst = list(range(5))

# 访问
lst[0] # 1
lst[-1] # 5
lst[1:3] # [2, 3]

# 修改
lst[0] = 10
lst.append(6)
lst.insert(0, 0)
lst.extend([7, 8])
lst.remove(10)
lst.pop() # 删除并返回最后一个
lst.pop(0) # 删除并返回指定位置

# 其他操作
len(lst)
lst.sort()
lst.reverse()
lst.index(3)
lst.count(2)
[1, 2] + [3, 4] # [1, 2, 3, 4]
[1] * 3 # [1, 1, 1]

# 列表推导式
[x**2 for x in range(10)]
[x for x in range(10) if x % 2 == 0]

元组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 创建
t = (1, 2, 3)
t = 1, 2, 3
t = tuple([1, 2, 3])

# 访问
t[0] # 1
t[1:3] # (2, 3)

# 特点:不可变
# t[0] = 10 # 报错

# 解包
a, b, c = t

字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 创建
d = {'name': '张三', 'age': 20}
d = dict(name='张三', age=20)

# 访问
d['name'] # '张三'
d.get('name') # '张三'
d.get('gender', '男') # 默认值

# 修改
d['name'] = '李四'
d['gender'] = '男'
d.update({'age': 25, 'city': '北京'})
d.pop('gender')
del d['age']

# 遍历
for key in d:
print(key, d[key])

for key, value in d.items():
print(key, value)

for key in d.keys():
print(key)

for value in d.values():
print(value)

# 字典推导式
{k: v**2 for k, v in {'a': 1, 'b': 2}.items()}

集合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 创建
s = {1, 2, 3}
s = set([1, 2, 2, 3]) # {1, 2, 3}

# 操作
s.add(4)
s.remove(1)
s.discard(10) # 不存在不报错

# 集合运算
a = {1, 2, 3}
b = {2, 3, 4}
a | b # 并集 {1, 2, 3, 4}
a & b # 交集 {2, 3}
a - b # 差集 {1}
a ^ b # 对称差 {1, 4}

四、控制流

条件语句

1
2
3
4
5
6
7
8
9
if condition:
pass
elif condition:
pass
else:
pass

# 三元表达式
value = a if condition else b

循环语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# for循环
for i in range(10):
print(i)

for item in iterable:
print(item)

for index, item in enumerate(lst):
print(index, item)

for key, value in dict.items():
print(key, value)

# while循环
while condition:
pass

# break, continue, pass

五、函数

定义函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def func(a, b):
return a + b

# 默认参数
def func(a, b=10):
return a + b

# 可变参数
def func(*args):
for arg in args:
print(arg)

def func(**kwargs):
for key, value in kwargs.items():
print(key, value)

# 组合
def func(a, b, *args, **kwargs):
pass

Lambda表达式

1
2
3
4
5
6
7
8
f = lambda x: x**2
f = lambda x, y: x + y

# 使用
lst = [1, 2, 3, 4, 5]
list(map(lambda x: x**2, lst))
list(filter(lambda x: x > 2, lst))
sorted(lst, key=lambda x: -x)

装饰器

1
2
3
4
5
6
7
8
9
10
11
def decorator(func):
def wrapper(*args, **kwargs):
print("before")
result = func(*args, **kwargs)
print("after")
return result
return wrapper

@decorator
def func():
print("func")

六、类和对象

定义类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def say_hello(self):
print(f"Hello, I'm {self.name}")

@property
def info(self):
return f"{self.name}, {self.age}"

# 继承
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade

def say_hello(self):
super().say_hello()
print(f"I'm in grade {self.grade}")

特殊方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MyClass:
def __init__(self, value):
self.value = value

def __str__(self):
return str(self.value)

def __repr__(self):
return f"MyClass({self.value})"

def __len__(self):
return len(self.value)

def __getitem__(self, key):
return self.value[key]

七、异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
try:
# 可能出错的代码
pass
except Exception as e:
# 异常处理
print(e)
else:
# 无异常时执行
pass
finally:
# 始终执行
pass

# 抛出异常
raise ValueError("invalid value")

八、文件操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 读取文件
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()
lines = f.readlines()
for line in f:
print(line)

# 写入文件
with open('file.txt', 'w', encoding='utf-8') as f:
f.write('content')
f.writelines(['line1\n', 'line2\n'])

# 追加
with open('file.txt', 'a', encoding='utf-8') as f:
f.write('new content')

九、模块和包

导入模块

1
2
3
4
5
import os
import os.path
from os import path
from os.path import join, exists
from os import * # 不推荐

常用标准库

1
2
3
4
5
6
7
8
9
10
import os           # 操作系统接口
import sys # 系统相关
import json # JSON处理
import datetime # 日期时间
import re # 正则表达式
import math # 数学函数
import random # 随机数
import collections # 高级数据结构
import itertools # 迭代工具
import functools # 函数工具

十、总结

Python基础要点:

  • 简洁的语法和动态类型
  • 四种内置数据结构:列表、元组、字典、集合
  • 支持函数式编程特性
  • 面向对象编程
  • 丰富的标准库

Python适合快速开发、数据处理、自动化脚本、Web开发、机器学习等场景。