一、Python安装与环境配置
重点:完成Python环境搭建,验证安装成功
步骤:
- 访问Python官网下载对应系统的安装包
- 安装时勾选"Add Python to PATH"(Windows)
- 终端验证安装:
python --version
# 输出示例:Python 3.9.7
二、基础语法入门
2.1 变量与数据类型
核心概念:动态类型、基本数据类型
# 变量声明
name = "Alice" # 字符串
age = 25 # 整数
price = 19.99 # 浮点数
is_student = True # 布尔值
print(type(name)) #
print(age + 5) # 30
2.2 字符串操作
重点:格式化输出、常用方法
# 字符串拼接
greeting = "Hello, " + name + "!"
print(greeting) # Hello, Alice!
# f-string格式化(Python 3.6+)
print(f"{name} is {age} years old")
# 常用方法
text = " Python is Awesome! "
print(text.strip()) # "Python is Awesome!"
print(text.lower()) # " python is awesome! "
print(text.replace("A", "a"))
三、流程控制
3.1 条件判断
结构:if-elif-else
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B") # 输出B
else:
print("C")
3.2 循环结构
核心循环:for循环、while循环
# for循环遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# while循环示例
count = 0
while count < 3:
print(f"Count: {count}")
count += 1
四、函数与模块
4.1 函数定义
要点:参数传递、返回值
def calculate_area(width, height):
"""计算矩形面积"""
return width * height
print(calculate_area(4, 5)) # 20
4.2 模块使用
重点:导入标准库和自定义模块
# 使用math模块
import math
print(math.sqrt(16)) # 4.0
# 创建自定义模块(保存为mymodule.py)
# 文件内容:
def greet(name):
return f"Hello, {name}!"
# 主程序中使用
from mymodule import greet
print(greet("Bob")) # Hello, Bob!
五、数据结构精要
5.1 列表(List)
核心操作:增删改查
numbers = [1, 2, 3]
numbers.append(4) # [1,2,3,4]
numbers.insert(1, 5) # [1,5,2,3,4]
print(numbers[1:3]) # [5,2]
5.2 字典(Dict)
关键特性:键值对存储
student = {
"name": "Alice",
"age": 24,
"courses": ["Math", "CS"]
}
print(student.get("age")) # 24
student["email"] = "alice@example.com"
5.3 元组(Tuple)
特点:不可变序列
coordinates = (10, 20)
x, y = coordinates # 元组解包
print(y) # 20
六、面向对象编程基础
6.1 类与对象
核心概念:封装、初始化方法
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says: Woof!")
my_dog = Dog("Buddy")
my_dog.bark() # Buddy says: Woof!
6.2 继承
实现方法:父类继承
class GoldenRetriever(Dog):
def play(self):
print(f"{self.name} is playing fetch!")
goldie = GoldenRetriever("Sunny")
goldie.bark() # 继承父类方法
goldie.play()
七、异常处理
基本结构:try-except
try:
num = int(input("输入数字: "))
print(10 / num)
except ValueError:
print("请输入有效数字!")
except ZeroDivisionError:
print("不能除以零!")
八、文件操作
基础读写:文本文件处理
# 写入文件
with open("diary.txt", "w") as file:
file.write("2023-07-20\nToday I learned Python!")
# 读取文件
with open("diary.txt") as file:
content = file.read()
print(content)
九、标准库示例
9.1 datetime模块
常用操作:时间处理
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M")) # 2023-07-20 14:30
9.2 random模块
随机功能:生成随机数
import random
print(random.randint(1, 100)) # 随机整数
print(random.choice(["a", "b", "c"])) # 随机选择
十、最佳实践建议
- 遵守PEP8代码规范
- 每个函数添加注释说明
- 优先使用内置函数和方法
- 使用虚拟环境管理项目依赖(如 conda、pyenv)
- 重要代码添加单元测试(使用unittest模块)
代码执行建议:
- 安装Python后创建专用项目目录
- 使用VS Code/PyCharm等IDE工具
- 复杂程序分模块编写
- 善用print()调试,后期过渡到调试器
学习路径建议:
- 先掌握基础语法 → 2. 完成小项目实践 → 3. 学习Web开发/数据分析等方向 → 4. 深入算法与设计模式
在学习Python的过程中,还是要多多实践通过不断的代码编写,来积累对问题的处理经验,同时提升对需求分析的准确性。
感谢关注收藏:)