一、Python 环境配置与运行

安装检查:

python --version

进入交互模式:

python

输出示例:


>>> print("Hello Python") Hello Python

运行脚本文件:

python hello.py

示例:

print("欢迎学习 Python!")


二、变量与数据类型

Python 是动态类型语言,不需要声明变量类型。

示例:

name = "Alice" age = 25 height = 1.68 is_student = True print(name, age, height, is_student)

数据类型:
类型示例描述
int100整数
float3.14浮点数
str"Hello"字符串
boolTrue/False布尔值
list[1,2,3]列表
tuple(1,2,3)元组
dict{"a":1,"b":2}字典

三、运算符与表达式

算术运算:

a, b = 10, 3 print(a + b, a - b, a * b, a / b, a // b, a % b, a ** b)

比较运算:

print(a > b, a == b, a != b)

逻辑运算:

print(a > 5 and b < 5) print(a > 5 or b > 10) print(not a == 10)


四、条件语句

示例:

score = 85 if score >= 90: print("优秀") elif score >= 60: print("及格") else: print("不及格")

Python 使用缩进控制逻辑,不使用大括号 {}。


五、循环语句

for 循环:

for i in range(1, 6): print("第", i, "次循环")

while 循环:

count = 0 while count < 5: print("当前计数:", count) count += 1

break / continue:

for i in range(10): if i == 5: break if i % 2 == 0: continue print(i)


六、列表与元组

列表操作:

fruits = ["apple", "banana", "cherry"] fruits.append("mango") fruits.remove("banana") print(fruits)

切片操作:

nums = [1, 2, 3, 4, 5] print(nums[1:4])

元组(不可变):

colors = ("red", "green", "blue") print(colors[0])


七、字典与集合

字典操作:

student = {"name": "Alice", "age": 22, "city": "Beijing"} print(student["name"]) student["age"] = 23 print(student)

集合(去重):

s = {1, 2, 3, 3, 2} s.add(5) print(s)


八、函数与作用域

定义函数:

def greet(name): print(f"你好,{name}!") greet("小明")

返回值:

def add(a, b): return a + b result = add(3, 5) print(result)

默认参数:

def power(x, n=2): return x ** n print(power(3))


九、匿名函数与高阶函数

lambda 表达式:

add = lambda a, b: a + b print(add(2, 5))

map 与 filter:

nums = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, nums)) even = list(filter(lambda x: x % 2 == 0, nums)) print(squared, even)


十、文件操作

读取文件:

with open("data.txt", "r", encoding="utf-8") as f: print(f.read())

写入文件:

with open("output.txt", "w", encoding="utf-8") as f: f.write("Hello Python 文件写入!")


十一、异常处理

示例:

try: num = int(input("输入一个数字:")) print(10 / num) except ValueError: print("请输入有效数字!") except ZeroDivisionError: print("除数不能为0!") finally: print("执行结束。")


十二、模块与包

导入模块:

import math print(math.sqrt(16))

自定义模块:

创建 mytools.py


def say_hello(): print("Hello from mytools!")

调用:


import mytools mytools.say_hello()


十三、面向对象编程

类与对象:

class Student: def __init__(self, name, score): self.name = name self.score = score def show(self): print(f"{self.name} 的成绩是 {self.score}") stu1 = Student("小李", 95) stu1.show()

继承与方法重写:

class Person: def speak(self): print("人类在说话") class Student(Person): def speak(self): print("学生在发言") s = Student() s.speak()


十四、迭代器与生成器

生成器函数:

def count_up_to(n): count = 1 while count <= n: yield count count += 1 for num in count_up_to(5): print(num)


十五、常用内置模块

时间与日期:

import time, datetime print(time.strftime("%Y-%m-%d %H:%M:%S")) print(datetime.date.today())

随机数:

import random print(random.randint(1, 10))

OS 文件操作:

import os print(os.getcwd()) os.mkdir("test_dir")

参考案例:www.phvrq.cn


十六、Python 虚拟环境与依赖管理

创建虚拟环境:

python -m venv venv

激活环境:

Windows:


venv\Scripts\activate

Linux:


source venv/bin/activate

安装依赖:

pip install flask requests

导出依赖:

pip freeze > requirements.txt


十七、实战项目:自动化批量重命名文件

示例脚本:

import os def rename_files(folder): for count, filename in enumerate(os.listdir(folder)): ext = os.path.splitext(filename)[1] new_name = f"file_{count+1}{ext}" os.rename(os.path.join(folder, filename), os.path.join(folder, new_name)) print("批量重命名完成!") rename_files("D:/images")


十八、Python 技能进阶方向

方向学习内容
Web 开发Flask、Django
数据分析Pandas、NumPy、Matplotlib
爬虫requests、BeautifulSoup
自动化运维paramiko、fabric
人工智能TensorFlow、PyTorch
办公自动化openpyxl、win32com

十九、掌握 Python 的思维与技巧

  1. 写代码时要实验性学习:随时打印变量,观察结果。

  2. 模块化思维:一个功能一个函数,清晰可维护。

  3. 多看标准库文档:Python 内置模块极其强大。

  4. 动手实践项目:比单纯记语法更重要。

掌握 Python 后,你能轻松实现脚本自动化、Web 应用、数据分析与 AI 项目,成为全能开发者。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐