1. Python简介与环境配置
Python是一种高级、解释型、通用的编程语言,由Guido van Rossum于1991年首次发布。
它以简洁明了的语法和强大的功能而闻名,广泛应用于Web开发、数据分析、人工智能、科学计算等领域。
1.1 Python的特点
-
简单易学:语法清晰,接近自然语言
-
跨平台:可在Windows、Linux、Mac等系统上运行
-
丰富的标准库:内置大量有用的模块和函数
-
支持多种编程范式:面向对象、函数式、过程式编程
-
动态类型:无需声明变量类型
-
自动内存管理:垃圾回收机制
1.2 安装Python
从Python官网:
https://soft.fengyunzhice.cn/softs/python.html?ver=gjc-1&bd_vid=10566552077197807836
安装的时候选择 Python to PATH 选项。
验证安装:
# 在命令行/终端中输入
python --version
# 或
python3 --version
1.3 运行Python代码
Python代码可以通过以下几种方式运行:
-
交互式解释器(REPL):
>>> print("Hello, World!") Hello, World!
-
脚本文件(.py):
# hello.py print("Hello, World!")# 在命令行运行 python hello.py
-
Jupyter Notebook等交互式环境
2. 基础语法
2.1 变量与数据类型
Python是动态类型语言,变量无需声明类型。
# 变量赋值
x = 10 # 整数
y = 3.14 # 浮点数
name = "Alice" # 字符串
is_active = True # 布尔值# 多变量赋值
a, b, c = 1, 2, "three"# 查看变量类型
print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'>
print(type(name)) # <class 'str'>
print(type(is_active))# <class 'bool'>
2.2 基本数据类型
-
数字类型:
-
int(整数):
10
,-5
,0
-
float(浮点数):
3.14
,-0.001
,2.0
-
complex(复数):
1 + 2j
-
-
布尔类型:
-
True
-
False
-
-
字符串:
-
用单引号或双引号括起来:
'hello'
,"world"
-
三引号用于多行字符串:
multi_line = """这是 一个 多行 字符串"""
-
2.3 类型转换
# 显式类型转换
int_num = int("123") # 字符串转整数
float_num = float("3.14") # 字符串转浮点数
str_num = str(123) # 数字转字符串
bool_val = bool(1) # 数字转布尔值 (0为False,非0为True)# 隐式类型转换(自动)
result = 3 + 4.5 # int + float = float
2.4 运算符
-
算术运算符:
a = 10 b = 3print(a + b) # 13 print(a - b) # 7 print(a * b) # 30 print(a / b) # 3.333... (浮点除法) print(a // b) # 3 (整数除法) print(a % b) # 1 (取模) print(a ** b) # 1000 (幂运算)
-
比较运算符:
print(a == b) # False
print(a != b) # True
print(a > b) # True
print(a < b) # False
print(a >= b) # True
print(a <= b) # False
-
逻辑运算符:
x = True y = Falseprint(x and y) # False print(x or y) # True print(not x) # False
-
赋值运算符:
a = 5 a += 2 # a = a + 2 → 7 a -= 1 # a = a - 1 → 6 a *= 3 # a = a * 3 → 18 a /= 2 # a = a / 2 → 9.0 a //= 2 # a = a // 2 → 4.0 a %= 3 # a = a % 3 → 1.0 a **= 2 # a = a ** 2 → 1.0
-
位运算符(较少使用):
a = 0b1010 # 10 b = 0b1100 # 12print(bin(a & b)) # 0b1000 (AND) print(bin(a | b)) # 0b1110 (OR) print(bin(a ^ b)) # 0b0110 (XOR) print(bin(~a)) # -0b1011 (NOT) print(bin(a << 2)) # 0b101000 (左移) print(bin(b >> 2)) # 0b0011 (右移)
2.5 输入输出
# 输出
print("Hello, World!") # 打印字符串
print("The value is", x) # 打印多个值,用空格分隔
print(f"The value is {x}") # f-string (Python 3.6+)# 输入
name = input("Enter your name: ") # 获取用户输入
age = int(input("Enter your age: ")) # 转换为整数
print(f"Hello, {name}! You are {age} years old.")
3. 控制结构
3.1 条件语句
# if-elif-else结构
age = 18if age < 13:print("Child")
elif 13 <= age < 18:print("Teenager")
else:print("Adult")# 简化写法
result = "Even" if age % 2 == 0 else "Odd"
print(result)
3.2 循环结构
-
while循环:
count = 0 while count < 5:print(count)count += 1 else:print("Loop completed") # 可选的else块
-
for循环:
# 遍历序列 fruits = ["apple", "banana", "cherry"] for fruit in fruits:print(fruit)# 使用range for i in range(5): # 0到4print(i)for i in range(2, 6): # 2到5print(i)for i in range(1, 10, 2): # 1到9,步长为2print(i)
-
循环控制:
for i in range(10):if i == 3:continue # 跳过本次迭代if i == 7:break # 终止循环print(i)
4. 数据结构
4.1 列表(List)
有序、可变、可重复元素的集合。
# 创建列表
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]# 访问元素
print(numbers[0]) # 1 (正向索引,从0开始)
print(numbers[-1]) # 5 (负向索引,-1表示最后一个)# 切片操作
print(numbers[1:3]) # [2, 3] (不包括结束索引)
print(numbers[:3]) # [1, 2, 3]
print(numbers[2:]) # [3, 4, 5]
print(numbers[::2]) # [1, 3, 5] (步长为2)# 修改列表
numbers[0] = 10 # 修改元素
numbers.append(6) # 添加元素到末尾
numbers.insert(2, 99) # 在索引2处插入99
numbers.remove(3) # 删除第一个值为3的元素
popped = numbers.pop() # 删除并返回最后一个元素
popped = numbers.pop(1) # 删除并返回索引1的元素# 列表操作
combined = numbers + fruits # 列表拼接
repeated = fruits * 2 # 列表重复
length = len(numbers) # 列表长度# 列表方法
numbers.sort() # 排序(原地修改)
sorted_numbers = sorted(numbers) # 返回新排序列表
numbers.reverse() # 反转列表
index = fruits.index("banana") # 查找元素索引
count = numbers.count(2) # 计数# 列表推导式
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
4.2 元组(Tuple)
有序、不可变、可重复元素的集合。
# 创建元组
point = (10, 20)
colors = ("red", "green", "blue")
single = (5,) # 单元素元组需要逗号# 访问元素
print(point[0]) # 10
print(colors[-1]) # blue# 元组不可变
# point[0] = 15 # 错误!不能修改元组# 元组解包
x, y = point
print(x, y) # 10 20# 元组方法
index = colors.index("green") # 查找索引
count = colors.count("red") # 计数
4.3 集合(Set)
无序、可变、不重复元素的集合。
# 创建集合
unique_numbers = {1, 2, 3, 3, 4} # {1, 2, 3, 4}
empty_set = set() # 不能用{},这是空字典# 集合操作
unique_numbers.add(5) # 添加元素
unique_numbers.remove(2) # 移除元素,不存在则报错
unique_numbers.discard(10) # 移除元素,不存在不报错
popped = unique_numbers.pop() # 随机移除并返回一个元素# 集合运算
a = {1, 2, 3}
b = {3, 4, 5}print(a | b) # 并集 {1, 2, 3, 4, 5}
print(a & b) # 交集 {3}
print(a - b) # 差集 {1, 2}
print(a ^ b) # 对称差集 {1, 2, 4, 5}# 集合推导式
squares = {x**2 for x in range(5)} # {0, 1, 4, 9, 16}
4.4 字典(Dictionary)
键值对的集合,键唯一且不可变。
# 创建字典
person = {"name": "Alice", "age": 25, "city": "New York"}
empty_dict = {}# 访问元素
print(person["name"]) # Alice
print(person.get("age")) # 25
print(person.get("email", "N/A")) # 键不存在返回默认值"N/A"# 修改字典
person["age"] = 26 # 修改值
person["email"] = "alice@example.com" # 添加新键值对
del person["city"] # 删除键值对
popped = person.pop("age") # 删除并返回值# 字典方法
keys = person.keys() # 所有键
values = person.values() # 所有值
items = person.items() # 所有键值对# 字典遍历
for key in person:print(key, person[key])for key, value in person.items():print(key, value)# 字典推导式
squares = {x: x**2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}
5. 函数
5.1 定义与调用函数
# 定义函数
def greet(name):"""这是一个问候函数""" # 文档字符串return f"Hello, {name}!"# 调用函数
message = greet("Alice")
print(message) # Hello, Alice!# 查看函数文档
print(greet.__doc__) # 这是一个问候函数
5.2 参数传递
# 位置参数
def power(base, exponent):return base ** exponentprint(power(2, 3)) # 8# 关键字参数
print(power(exponent=3, base=2)) # 8# 默认参数
def greet(name, greeting="Hello"):return f"{greeting}, {name}!"print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Hi")) # Hi, Bob!# 可变参数 (*args)
def sum_numbers(*args):return sum(args)print(sum_numbers(1, 2, 3)) # 6
print(sum_numbers(4, 5, 6, 7)) # 22# 关键字可变参数 (**kwargs)
def print_info(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")print_info(name="Alice", age=25, city="NY")
# name: Alice
# age: 25
# city: NY
5.3 返回值
# 多返回值
def min_max(numbers):return min(numbers), max(numbers)minimum, maximum = min_max([3, 1, 4, 1, 5, 9, 2])
print(minimum, maximum) # 1 9# 返回函数
def make_adder(x):def adder(y):return x + yreturn adderadd5 = make_adder(5)
print(add5(3)) # 8
5.4 作用域
x = 10 # 全局变量def my_func():global x # 声明使用全局变量x = 20 # 修改全局变量y = 30 # 局部变量my_func()
print(x) # 20
# print(y) # 错误,y未定义
5.5 Lambda函数
匿名函数,用于简单操作。
# 简单lambda
square = lambda x: x**2
print(square(5)) # 25# 作为参数
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25]# 排序
pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
pairs.sort(key=lambda pair: pair[1]) # 按第二个元素排序
print(pairs) # [(1, 'one'), (3, 'three'), (2, 'two')]
6. 文件操作
6.1 文件读写
# 写入文件
with open("example.txt", "w", encoding="utf-8") as f:f.write("Hello, World!\n")f.write("This is a text file.\n")# 读取文件
with open("example.txt", "r", encoding="utf-8") as f:content = f.read() # 读取全部内容print(content)# 回到文件开头f.seek(0)lines = f.readlines() # 读取所有行print(lines)# 逐行读取
with open("example.txt", "r", encoding="utf-8") as f:for line in f:print(line.strip()) # 去除换行符
6.2 文件模式
-
'r'
:读取(默认) -
'w'
:写入(会覆盖) -
'a'
:追加 -
'x'
:创建新文件并写入 -
'b'
:二进制模式 -
't'
:文本模式(默认) -
'+'
:读写模式
6.3 CSV文件操作
import csv# 写入CSV
with open("data.csv", "w", newline="") as csvfile:writer = csv.writer(csvfile)writer.writerow(["Name", "Age", "City"])writer.writerow(["Alice", 25, "New York"])writer.writerow(["Bob", 30, "Los Angeles"])# 读取CSV
with open("data.csv", "r") as csvfile:reader = csv.reader(csvfile)for row in reader:print(row)
7. 异常处理
try:# 可能出错的代码num = int(input("Enter a number: "))result = 10 / numprint("Result:", result)
except ValueError:print("Invalid input. Please enter a number.")
except ZeroDivisionError:print("Cannot divide by zero.")
except Exception as e:print(f"An error occurred: {e}")
else:print("No errors occurred.") # 无异常时执行
finally:print("This always executes.") # 无论是否有异常都执行# 自定义异常
class MyError(Exception):passdef check_value(x):if x < 0:raise MyError("Value cannot be negative")try:check_value(-5)
except MyError as e:print(e)
8. 面向对象编程
8.1 类与对象
class Dog:# 类属性species = "Canis familiaris"# 初始化方法def __init__(self, name, age):self.name = name # 实例属性self.age = age# 实例方法def bark(self):return f"{self.name} says woof!"# 字符串表示def __str__(self):return f"{self.name} is {self.age} years old"# 创建实例
dog1 = Dog("Buddy", 5)
dog2 = Dog("Molly", 3)# 访问属性和方法
print(dog1.name) # Buddy
print(dog2.bark()) # Molly says woof!
print(dog1) # Buddy is 5 years old
print(Dog.species) # Canis familiaris
8.2 继承
class Bulldog(Dog): # 继承Dog类def bark(self):return f"{self.name} says woof loudly!"# 新增方法def run(self, speed):return f"{self.name} runs at {speed} mph"bulldog = Bulldog("Spike", 4)
print(bulldog.bark()) # Spike says woof loudly!
print(bulldog.run(10)) # Spike runs at 10 mph
8.3 封装
class BankAccount:def __init__(self, account_holder, balance=0):self._account_holder = account_holder # 保护属性self.__balance = balance # 私有属性# 公开方法def deposit(self, amount):if amount > 0:self.__balance += amountreturn Truereturn Falsedef withdraw(self, amount):if 0 < amount <= self.__balance:self.__balance -= amountreturn Truereturn Falsedef get_balance(self):return self.__balanceaccount = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance()) # 1300
# print(account.__balance) # 错误,无法直接访问私有属性
8.4 多态
class Cat:def speak(self):return "Meow"class Duck:def speak(self):return "Quack"def animal_sound(animal):print(animal.speak())cat = Cat()
duck = Duck()animal_sound(cat) # Meow
animal_sound(duck) # Quack
9. 模块与包
9.1 导入模块
# 导入整个模块
import math
print(math.sqrt(16)) # 4.0# 导入特定函数/类
from random import randint
print(randint(1, 10)) # 随机整数# 导入并重命名
import numpy as np
from datetime import datetime as dt# 导入所有内容(不推荐)
from os import *
9.2 创建模块
-
创建
mymodule.py
:def greet(name):return f"Hello, {name}!"def add(a, b):return a + bPI = 3.14159
-
使用模块:
import mymoduleprint(mymodule.greet("Alice")) # Hello, Alice! print(mymodule.add(2, 3)) # 5 print(mymodule.PI) # 3.14159
9.3 创建包
包是包含__init__.py
文件的目录。
目录结构:
mypackage/__init__.pymodule1.pymodule2.pysubpackage/__init__.pymodule3.py
使用包:
from mypackage import module1
from mypackage.subpackage import module3
10. 常用标准库
10.1 os模块
import os# 文件和目录操作
print(os.getcwd()) # 当前工作目录
os.chdir("/path/to/dir") # 改变工作目录
print(os.listdir()) # 列出目录内容# 路径操作
file_path = os.path.join("folder", "file.txt") # 跨平台路径拼接
print(os.path.exists(file_path)) # 检查路径是否存在
print(os.path.isfile(file_path)) # 检查是否是文件
print(os.path.isdir(file_path)) # 检查是否是目录# 环境变量
print(os.environ.get("HOME")) # 获取环境变量
10.2 sys模块
import sys# 命令行参数
print(sys.argv) # 命令行参数列表# 退出程序
# sys.exit(0) # 正常退出
# sys.exit(1) # 异常退出# Python路径
print(sys.path) # Python模块搜索路径# 版本信息
print(sys.version)
10.3 datetime模块
from datetime import datetime, date, time, timedelta# 当前时间
now = datetime.now()
print(now) # 2023-05-15 14:30:00.123456# 创建特定日期时间
dt = datetime(2023, 5, 15, 14, 30)
print(dt.year, dt.month, dt.day) # 2023 5 15# 格式化
print(dt.strftime("%Y-%m-%d %H:%M:%S")) # 2023-05-15 14:30:00# 解析字符串
dt = datetime.strptime("2023-05-15", "%Y-%m-%d")# 时间运算
tomorrow = dt + timedelta(days=1)
print(tomorrow) # 2023-05-16 00:00:00
10.4 json模块
import json# Python对象转JSON字符串
data = {"name": "Alice","age": 25,"is_active": True,"skills": ["Python", "Java"]
}json_str = json.dumps(data, indent=2)
print(json_str)# JSON字符串转Python对象
parsed_data = json.loads(json_str)
print(parsed_data["name"]) # Alice# 文件操作
with open("data.json", "w") as f:json.dump(data, f)with open("data.json", "r") as f:loaded_data = json.load(f)
10.5 random模块
import random# 随机数
print(random.random()) # [0.0, 1.0) 的随机浮点数
print(random.uniform(1, 10)) # [1, 10] 的随机浮点数
print(random.randint(1, 6)) # [1, 6] 的随机整数# 序列操作
items = ["apple", "banana", "cherry"]
print(random.choice(items)) # 随机选择一个元素
random.shuffle(items) # 打乱序列
print(items)
print(random.sample(items, 2)) # 随机选择k个不重复元素
11. 进阶特性
11.1 生成器
# 生成器函数
def count_down(n):while n > 0:yield nn -= 1for num in count_down(5):print(num) # 5, 4, 3, 2, 1# 生成器表达式
squares = (x**2 for x in range(10))
print(next(squares)) # 0
print(next(squares)) # 1
11.2 装饰器
# 简单装饰器
def my_decorator(func):def wrapper():print("Before function call")func()print("After function call")return wrapper@my_decorator
def say_hello():print("Hello!")say_hello()
# Before function call
# Hello!
# After function call# 带参数的装饰器
def repeat(n):def decorator(func):def wrapper(*args, **kwargs):for _ in range(n):result = func(*args, **kwargs)return resultreturn wrapperreturn decorator@repeat(3)
def greet(name):print(f"Hello, {name}!")greet("Alice")
# Hello, Alice!
# Hello, Alice!
# Hello, Alice!
11.3 上下文管理器
# 使用with语句
with open("file.txt", "r") as f:content = f.read()# 自定义上下文管理器
class Timer:def __enter__(self):import timeself.start = time.time()return selfdef __exit__(self, exc_type, exc_val, exc_tb):import timeself.end = time.time()print(f"Elapsed time: {self.end - self.start:.2f} seconds")with Timer():# 执行一些操作sum(range(1000000)))
12. Python最佳实践
-
遵循PEP 8风格指南:
-
使用4个空格缩进
-
行长度不超过79字符
-
导入顺序:标准库、第三方库、本地库
-
命名约定:
-
变量和函数:
lower_case_with_underscores
-
常量:
UPPER_CASE_WITH_UNDERSCORES
-
类:
CamelCase
-
-
-
使用虚拟环境:
python -m venv myenv # 创建虚拟环境 source myenv/bin/activate # 激活(Linux/Mac) myenv\Scripts\activate # 激活(Windows) deactivate # 退出虚拟环境
-
使用类型提示(Python 3.5+):
def greet(name: str) -> str:return f"Hello, {name}!"from typing import List, Dict, Optionaldef process_items(items: List[str], counts: Dict[str, int]) -> Optional[int]:# 函数体pass
-
编写文档字符串:
def add(a, b):"""计算两个数的和参数:a (int): 第一个数b (int): 第二个数返回:int: 两个数的和"""return a + b
-
单元测试:
import unittestclass TestMath(unittest.TestCase):def test_add(self):self.assertEqual(add(2, 3), 5)self.assertEqual(add(-1, 1), 0)def test_divide(self):with self.assertRaises(ValueError):divide(10, 0)if __name__ == "__main__":unittest.main()
13. 总结
本快速回顾涵盖了Python编程的基础知识,包括:
-
基础语法:变量、数据类型、运算符、控制结构
-
数据结构:列表、元组、集合、字典
-
函数:定义、参数传递、作用域、lambda
-
文件操作:读写文本和CSV文件
-
异常处理:try-except结构
-
面向对象编程:类、继承、封装、多态
-
模块与包:导入、创建和使用
-
常用标准库:os、sys、datetime、json、random
-
进阶特性:生成器、装饰器、上下文管理器
-
最佳实践:代码风格、虚拟环境、类型提示、文档、测试
Python以其简洁的语法和强大的功能,成为最受欢迎的编程语言之一。掌握这些基础知识后,你可以继续学习特定领域的Python应用,如Web开发(Django、Flask)、数据分析(Pandas、NumPy)、机器学习(Scikit-learn、TensorFlow)等。