一、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 b = 3.14 c = 1 + 2j
s = "Hello" s = 'World' s = """多行 字符串"""
flag = True flag = False
value = None
int("123") str(123) float("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] s[-1] s[0:5] s[6:] s[::-1]
s.lower() s.upper() s.split() '-'.join(['a','b']) s.replace('World', 'Python') s.startswith('Hello') s.endswith('World') 'Hello' in s len(s)
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] lst[-1] lst[1: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] * 3
[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] t[1:3]
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])
s.add(4) s.remove(1) s.discard(10)
a = {1, 2, 3} b = {2, 3, 4} a | b a & b a - b a ^ b
|
四、控制流
条件语句
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 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 condition: 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 import datetime import re import math import random import collections import itertools import functools
|
十、总结
Python基础要点:
- 简洁的语法和动态类型
- 四种内置数据结构:列表、元组、字典、集合
- 支持函数式编程特性
- 面向对象编程
- 丰富的标准库
Python适合快速开发、数据处理、自动化脚本、Web开发、机器学习等场景。