跳到主要内容
Python 零基础学习指南 | 极客日志
Python AI 算法
Python 零基础学习指南 提供 Python 零基础学习指南,涵盖环境搭建、基础语法、数据类型、控制流程、函数、面向对象编程、模块包、文件操作及异常处理。包含实战项目如任务管理器和 ATM 模拟。适合初学者系统掌握 Python 核心知识,为 Web 开发、数据分析及人工智能方向打下基础。
月光旅人 发布于 2026/3/30 更新于 2026/5/26 29 浏览Python 零基础学习指南
🐍 从零开始,轻松掌握 Python - 最适合初学者的 Python 学习路径
第 1 章:Python 简介与环境搭建
🤔 什么是 Python?
想象一下,如果编程语言是工具,那么 Python 就像是一把瑞士军刀 - 简单易用,功能强大!
Python 的特点:
🎯 简单易学 :语法接近自然语言
📖 可读性强 :代码像写文章一样清晰
🌍 应用广泛 :从网站到人工智能都能用
🆓 完全免费 :开源且免费使用
🛠️ 安装 Python
Windows 用户:
访问 Python 官网
下载最新版本(推荐 3.9+)
安装时务必勾选 "Add Python to PATH"
验证安装:
🎮 第一个 Python 程序
让我们写第一个程序 - 向世界问好!
print ("Hello, World!" )
print ("欢迎来到 Python 的世界!" )
运行结果:
Hello, World! 欢迎来到 Python 的世界!
💡 学习提示 :print() 是 Python 中最常用的函数,用来显示信息。
🎯 Python 能做什么?
领域 应用 热门库 🌐 网站开发 制作网站和 API Django, Flask 🤖 人工智能 机器学习、深度学习 TensorFlow, PyTorch 📊 数据分析 数据处理和可视化 Pandas, Matplotlib 🎮 游戏开发 2D 游戏制作 Pygame
✅ 第 1 章练习
name = "你的名字"
age = 你的年龄
hobby = "你的爱好"
print (f"大家好,我是{name} " )
print (f"我今年{age} 岁" )
print (f"我喜欢{hobby} " )
第 2 章:基础语法入门
🏷️ 变量 - 给数据起名字
name = "小明"
age = 18
height = 1.75
is_student = True
print (f"姓名:{name} " )
print (f"年龄:{age} " )
print (f"身高:{height} 米" )
print (f"是学生:{is_student} " )
📝 变量命名规则 user_name = "张三"
userAge = 25
score1 = 95
_private = "私有变量"
💬 注释 - 给代码写说明 注释就像是给代码写的小纸条 ,帮助别人(和未来的你)理解代码。
""" 这是多行注释
可以写很多行
通常用来写详细说明
"""
name = "Python"
🧮 基本运算
a = 10
b = 3
print (f"{a} + {b} = {a + b} " )
print (f"{a} - {b} = {a - b} " )
print (f"{a} * {b} = {a * b} " )
print (f"{a} / {b} = {a / b} " )
print (f"{a} // {b} = {a // b} " )
print (f"{a} % {b} = {a % b} " )
print (f"{a} ** {b} = {a ** b} " )
🔄 比较和逻辑运算
x = 5
y = 3
print (f"{x} > {y} = {x > y} " )
print (f"{x} == {y} = {x == y} " )
print (f"{x} != {y} = {x != y} " )
is_sunny = True
is_warm = False
print (f"晴天且温暖:{is_sunny and is_warm} " )
print (f"晴天或温暖:{is_sunny or is_warm} " )
print (f"不是晴天:{not is_sunny} " )
📥📤 输入和输出
name = input ("请输入你的名字:" )
age_str = input ("请输入你的年龄:" )
age = int (age_str)
print (f"你好,{name} !" )
print (f"你今年{age} 岁了。" )
next_year_age = age + 1
print (f"明年你就{next_year_age} 岁了!" )
🎨 字符串格式化 name = "小红"
score = 95.5
subject = "数学"
print (f"{name} 的{subject} 成绩是{score} 分" )
print ("{}的{}成绩是{}分" .format (name, subject, score))
print ("%s的%s成绩是%.1f分" % (name, subject, score))
⚠️ 常见错误
if True :
print ("这会报错" )
if True :
print ("这是正确的" )
print (Name)
name = "Python"
print (name)
✅ 第 2 章练习
num1 = float (input ("请输入第一个数字:" ))
num2 = float (input ("请输入第二个数字:" ))
print (f"加法:{num1} + {num2} = {num1 + num2} " )
print (f"减法:{num1} - {num2} = {num1 - num2} " )
print (f"乘法:{num1} * {num2} = {num1 * num2} " )
if num2 != 0 :
print (f"除法:{num1} / {num2} = {num1 / num2} " )
else :
print ("除数不能为 0!" )
age = int (input ("请输入你的年龄:" ))
if age < 0 :
print ("年龄不能为负数!" )
elif age <= 12 :
print ("你还是个孩子" )
elif age <= 18 :
print ("你是青少年" )
elif age <= 60 :
print ("你是成年人" )
else :
print ("你是老年人" )
第 3 章:数据类型详解
🔢 数字类型 Python 中的数字就像现实中的数字一样,有不同的类型。
整数 (int)
age = 25
temperature = -10
big_number = 1000000
print (f"年龄:{age} " )
print (f"温度:{temperature} °C" )
print (f"大数字:{big_number:,} " )
浮点数 (float)
height = 1.75
pi = 3.14159
price = 99.99
print (f"身高:{height} 米" )
print (f"圆周率:{pi} " )
print (f"价格:¥{price} " )
数字运算技巧
import math
number = 16
print (f"平方根:{math.sqrt(number)} " )
print (f"向上取整:{math.ceil(3.2 )} " )
print (f"向下取整:{math.floor(3.8 )} " )
print (f"四舍五入:{round (3.14159 , 2 )} " )
📝 字符串 (str)
message = "Hello, Python!"
name = '小明'
long_text = """
这是一个 多行字符串
可以写很多行
"""
print (message)
print (name)
print (long_text)
字符串操作 text = "Python 编程"
print (f"字符串长度:{len (text)} " )
print (f"第一个字符:{text[0 ]} " )
print (f"最后一个字符:{text[-1 ]} " )
print (f"前 3 个字符:{text[:3 ]} " )
print (f"后 2 个字符:{text[-2 :]} " )
print (f"中间部分:{text[2 :5 ]} " )
字符串方法 sentence = " Hello, World! "
print (f"原始:'{sentence} '" )
print (f"大写:{sentence.upper()} " )
print (f"小写:{sentence.lower()} " )
print (f"去空格:'{sentence.strip()} '" )
print (f"替换:{sentence.replace('World' , 'Python' )} " )
print (f"分割:{sentence.split(',' )} " )
📋 列表 (list)
fruits = ["苹果" , "香蕉" , "橙子" ]
numbers = [1 , 2 , 3 , 4 , 5 ]
mixed = ["Python" , 3.14 , True , [1 , 2 , 3 ]]
print (f"水果:{fruits} " )
print (f"数字:{numbers} " )
print (f"混合:{mixed} " )
列表操作 shopping_list = ["牛奶" , "面包" ]
shopping_list.append("鸡蛋" )
shopping_list.insert(0 , "水果" )
print (f"购物清单:{shopping_list} " )
shopping_list.remove("面包" )
last_item = shopping_list.pop()
print (f"删除后:{shopping_list} " )
print (f"删除的物品:{last_item} " )
print (f"清单长度:{len (shopping_list)} " )
print (f"第一个物品:{shopping_list[0 ]} " )
列表推导式 - 快速创建列表
squares = []
for i in range (1 , 6 ):
squares.append(i ** 2 )
squares = [i ** 2 for i in range (1 , 6 )]
print (f"平方数:{squares} " )
even_squares = [i ** 2 for i in range (1 , 11 ) if i % 2 == 0 ]
print (f"偶数的平方:{even_squares} " )
📦 元组 (tuple)
coordinates = (10 , 20 )
colors = ("红" , "绿" , "蓝" )
single_item = (42 ,)
print (f"坐标:{coordinates} " )
print (f"颜色:{colors} " )
x, y = coordinates
print (f"x 坐标:{x} , y 坐标:{y} " )
def get_name_age ():
return "小明" , 18
name, age = get_name_age()
print (f"姓名:{name} , 年龄:{age} " )
📖 字典 (dict)
student = {"姓名" : "小红" , "年龄" : 20 , "专业" : "计算机科学" , "成绩" : [85 , 92 , 78 ]}
print (f"学生信息:{student} " )
print (f"姓名:{student['姓名' ]} " )
print (f"年龄:{student.get('年龄' , '未知' )} " )
student["年龄" ] = 21
student["学号" ] = "2023001"
print (f"更新后:{student} " )
for key, value in student.items():
print (f"{key} : {value} " )
🎯 集合 (set)
fruits = {"苹果" , "香蕉" , "橙子" , "苹果" }
print (f"水果集合:{fruits} " )
set1 = {1 , 2 , 3 , 4 }
set2 = {3 , 4 , 5 , 6 }
print (f"交集:{set1 & set2} " )
print (f"并集:{set1 | set2} " )
print (f"差集:{set1 - set2} " )
all_students = ["小明" , "小红" , "小刚" , "小明" , "小红" ]
unique_students = set (all_students)
print (f"去重后的学生:{unique_students} " )
🎨 数据类型转换
number_str = "123"
float_str = "3.14"
bool_str = "True"
print (f"字符串转整数:{int (number_str)} " )
print (f"字符串转浮点数:{float (float_str)} " )
print (f"数字转字符串:{str (456 )} " )
print (f"列表转集合:{set ([1 , 2 , 2 , 3 ])} " )
age = 25
print (f"age 的类型:{type (age)} " )
print (f"是否为整数:{isinstance (age, int )} " )
✅ 第 3 章练习
students = {"小明" : [85 , 92 , 78 ], "小红" : [90 , 88 , 95 ], "小刚" : [76 , 84 , 89 ]}
for name, scores in students.items():
average = sum (scores) / len (scores)
print (f"{name} 的平均分:{average:.1 f} " )
all_scores = []
for scores in students.values():
all_scores.extend(scores)
print (f"最高分:{max (all_scores)} " )
print (f"最低分:{min (all_scores)} " )
prices = {"苹果" : 5.0 , "香蕉" : 3.0 , "橙子" : 4.5 , "牛奶" : 12.0 }
cart = []
cart.append("苹果" )
cart.append("牛奶" )
cart.append("苹果" )
total = 0
for item in cart:
total += prices[item]
print (f"添加 {item} ,价格:¥{prices[item]} " )
print (f"总价:¥{total} " )
from collections import Counter
item_count = Counter(cart)
print (f"购买清单:{dict (item_count)} " )
第 4 章:控制流程
🤔 条件判断 (if 语句) 条件判断就像人生的选择题 ,根据不同情况做不同的事。
weather = "晴天"
if weather == "晴天" :
print ("今天天气不错,出去走走吧!" )
elif weather == "雨天" :
print ("下雨了,记得带伞!" )
else :
print ("不管什么天气,保持好心情!" )
实际应用:成绩等级判定 score = int (input ("请输入你的成绩:" ))
if score >= 90 :
grade = "A"
comment = "优秀!"
elif score >= 80 :
grade = "B"
comment = "良好!"
elif score >= 70 :
grade = "C"
comment = "中等"
elif score >= 60 :
grade = "D"
comment = "及格"
else :
grade = "F"
comment = "需要努力"
print (f"成绩:{score} 分" )
print (f"等级:{grade} " )
print (f"评价:{comment} " )
复杂条件判断 age = 20
has_license = True
has_car = False
if age >= 18 and has_license:
if has_car:
print ("你可以开车出行!" )
else :
print ("你可以租车或借车!" )
elif age >= 18 :
print ("你需要先考驾照!" )
else :
print ("你还太年轻,不能开车!" )
status = "成年人" if age >= 18 else "未成年人"
print (f"你是:{status} " )
🔄 循环语句
for 循环 - 已知次数的循环
print ("倒计时:" )
for i in range (5 , 0 , -1 ):
print (f"{i} ..." )
print ("发射!🚀" )
fruits = ["苹果" , "香蕉" , "橙子" ]
print ("\n我喜欢的水果:" )
for fruit in fruits:
print (f"- {fruit} " )
print ("\n带编号的水果:" )
for index, fruit in enumerate (fruits, 1 ):
print (f"{index} . {fruit} " )
while 循环 - 条件循环
import random
secret_number = random.randint(1 , 100 )
attempts = 0
max_attempts = 7
print ("🎯 猜数字游戏!我想了一个 1-100 的数字" )
print (f"你有{max_attempts} 次机会!" )
while attempts < max_attempts:
guess = int (input ("请输入你的猜测:" ))
attempts += 1
if guess == secret_number:
print (f"🎉 恭喜!你用{attempts} 次就猜对了!" )
break
elif guess < secret_number:
print ("太小了!" )
else :
print ("太大了!" )
remaining = max_attempts - attempts
if remaining > 0 :
print (f"还有{remaining} 次机会" )
else :
print (f"😢 游戏结束!答案是{secret_number} " )
循环控制
print ("寻找 1-20 中能被 3 整除但不能被 6 整除的数:" )
for num in range (1 , 21 ):
if num % 3 != 0 :
continue
if num % 6 == 0 :
continue
print (num, end=" " )
print ()
🎯 实际应用案例
案例 1:密码强度检查 def check_password_strength (password ):
"""检查密码强度"""
score = 0
feedback = []
if len (password) >= 8 :
score += 1
else :
feedback.append("密码至少需要 8 位" )
if any (c.isdigit() for c in password):
score += 1
else :
feedback.append("需要包含数字" )
if any (c.islower() for c in password):
score += 1
else :
feedback.append("需要包含小写字母" )
if any (c.isupper() for c in password):
score += 1
else :
feedback.append("需要包含大写字母" )
special_chars = "!@#$%^&*"
if any (c in special_chars for c in password):
score += 1
else :
feedback.append("需要包含特殊字符" )
if score >= 4 :
strength = "强"
elif score >= 3 :
strength = "中等"
else :
strength = "弱"
return strength, feedback
test_passwords = ["123456" , "Password1" , "MyP@ssw0rd" ]
for pwd in test_passwords:
strength, tips = check_password_strength(pwd)
print (f"\n密码:{pwd} " )
print (f"强度:{strength} " )
if tips:
print ("建议:" )
for tip in tips:
print (f" - {tip} " )
✅ 第 4 章练习 print ("九九乘法表:" )
for i in range (1 , 10 ):
for j in range (1 , i + 1 ):
result = i * j
print (f"{j} ×{i} ={result:2d} " , end=" " )
print ()
balance = 1000
while True :
print ("\n=== 欢迎使用 ATM ===" )
print ("1. 查询余额" )
print ("2. 存款" )
print ("3. 取款" )
print ("4. 退出" )
choice = input ("请选择操作(1-4):" )
if choice == "1" :
print (f"当前余额:¥{balance} " )
elif choice == "2" :
amount = float (input ("请输入存款金额:" ))
if amount > 0 :
balance += amount
print (f"存款成功!当前余额:¥{balance} " )
else :
print ("存款金额必须大于 0!" )
elif choice == "3" :
amount = float (input ("请输入取款金额:" ))
if amount > balance:
print ("余额不足!" )
elif amount <= 0 :
print ("取款金额必须大于 0!" )
else :
balance -= amount
print (f"取款成功!当前余额:¥{balance} " )
elif choice == "4" :
print ("谢谢使用,再见!" )
break
else :
print ("无效选择,请重新输入!" )
第 5 章:函数的世界
🔧 什么是函数? 函数就像一个魔法盒子 ,你给它一些材料(参数),它就能变出你想要的东西(返回值)。
def greet (name ):
"""向某人问好的函数"""
return f"你好,{name} !"
message = greet("小明" )
print (message)
🎯 函数的基本结构 def function_name (参数 1 , 参数 2 ):
"""函数的说明文档"""
result = 参数 1 + 参数 2
return result
📝 实际例子:计算器函数 def calculator (num1, num2, operation ):
"""简单计算器函数
参数:
num1: 第一个数字
num2: 第二个数字
operation: 运算符 (+, -, *, /)
返回:
计算结果
"""
if operation == "+" :
return num1 + num2
elif operation == "-" :
return num1 - num2
elif operation == "*" :
return num1 * num2
elif operation == "/" :
if num2 != 0 :
return num1 / num2
else :
return "错误:除数不能为 0"
else :
return "错误:不支持的运算符"
print (calculator(10 , 5 , "+" ))
print (calculator(10 , 5 , "/" ))
print (calculator(10 , 0 , "/" ))
🎨 参数的不同类型
1. 默认参数 def introduce (name, age, city="北京" ):
"""自我介绍函数,城市有默认值"""
return f"我是{name} ,今年{age} 岁,来自{city} "
print (introduce("小明" , 20 ))
print (introduce("小红" , 22 , "上海" ))
2. 关键字参数 def order_coffee (size, coffee_type, sugar=False , milk=False ):
"""点咖啡函数"""
order = f"一杯{size} 的{coffee_type} "
if sugar:
order += ",加糖"
if milk:
order += ",加奶"
return order
print (order_coffee(coffee_type="拿铁" , size="大杯" , milk=True ))
3. 可变参数 def calculate_average (*numbers ):
"""计算任意个数字的平均值"""
if not numbers:
return 0
total = sum (numbers)
count = len (numbers)
return total / count
print (calculate_average(85 , 92 , 78 ))
print (calculate_average(90 , 88 , 95 , 87 , 91 ))
4. 关键字可变参数 def create_profile (name, **info ):
"""创建个人档案"""
profile = f"姓名:{name} \n"
for key, value in info.items():
profile += f"{key} :{value} \n"
return profile
print (create_profile("小明" , 年龄=20 , 专业="计算机科学" , 爱好="编程" , 城市="北京" ))
🌟 函数的高级特性
Lambda 函数(匿名函数)
def square (x ):
return x ** 2
square_lambda = lambda x: x ** 2
print (square(5 ))
print (square_lambda(5 ))
students = [
{"name" : "小明" , "score" : 85 },
{"name" : "小红" , "score" : 92 },
{"name" : "小刚" , "score" : 78 }
]
sorted_students = sorted (students, key=lambda s: s["score" ], reverse=True )
for student in sorted_students:
print (f"{student['name' ]} : {student['score' ]} " )
装饰器 - 给函数加特效 def timer (func ):
"""计时装饰器"""
import time
def wrapper (*args, **kwargs ):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print (f"函数 {func.__name__} 执行时间:{end_time - start_time:.4 f} 秒" )
return result
return wrapper
@timer
def slow_function ():
"""一个慢函数"""
import time
time.sleep(1 )
return "完成!"
result = slow_function()
🎯 实际应用:学生管理系统
students_db = []
def add_student (name, age, grade ):
"""添加学生"""
student = {
"id" : len (students_db) + 1 ,
"name" : name,
"age" : age,
"grade" : grade,
"courses" : []
}
students_db.append(student)
return f"学生 {name} 添加成功,ID: {student['id' ]} "
def find_student (student_id ):
"""查找学生"""
for student in students_db:
if student["id" ] == student_id:
return student
return None
def add_course (student_id, course, score ):
"""添加课程成绩"""
student = find_student(student_id)
if student:
student["courses" ].append({"course" : course, "score" : score})
return f"为 {student['name' ]} 添加课程 {course} 成功"
return "学生不存在"
def calculate_gpa (student_id ):
"""计算 GPA"""
student = find_student(student_id)
if student and student["courses" ]:
total_score = sum (course["score" ] for course in student["courses" ])
return total_score / len (student["courses" ])
return 0
def display_student (student_id ):
"""显示学生信息"""
student = find_student(student_id)
if student:
print (f"\n=== 学生信息 ===" )
print (f"ID: {student['id' ]} " )
print (f"姓名:{student['name' ]} " )
print (f"年龄:{student['age' ]} " )
print (f"年级:{student['grade' ]} " )
print (f"GPA: {calculate_gpa(student_id):.2 f} " )
if student["courses" ]:
print ("课程成绩:" )
for course in student["courses" ]:
print (f" {course['course' ]} : {course['score' ]} " )
else :
print ("学生不存在" )
print (add_student("小明" , 20 , "大二" ))
print (add_student("小红" , 19 , "大一" ))
print (add_course(1 , "数学" , 85 ))
print (add_course(1 , "英语" , 92 ))
print (add_course(2 , "物理" , 88 ))
display_student(1 )
display_student(2 )
✅ 第 5 章练习 import random
import string
def generate_password (length=8 , include_symbols=True ):
"""生成随机密码
参数:
length: 密码长度
include_symbols: 是否包含特殊字符
"""
letters = string.ascii_letters
digits = string.digits
symbols = "!@#$%^&*"
char_pool = letters + digits
if include_symbols:
char_pool += symbols
password = '' .join(random.choice(char_pool) for _ in range (length))
return password
for i in range (3 ):
pwd = generate_password(12 , True )
print (f"密码 {i+1 } : {pwd} " )
def analyze_text (text ):
"""分析文本的各种统计信息"""
char_count = len (text)
word_count = len (text.split())
sentence_count = text.count('.' ) + text.count('!' ) + text.count('?' )
char_freq = {}
for char in text.lower():
if char.isalpha():
char_freq[char] = char_freq.get(char, 0 ) + 1
most_common_char = max (char_freq, key=char_freq.get) if char_freq else None
return {
"字符数" : char_count,
"单词数" : word_count,
"句子数" : sentence_count,
"最常见字符" : most_common_char,
"字符频率" : char_freq
}
sample_text = "Python is a great programming language. It's easy to learn and powerful!"
result = analyze_text(sample_text)
print ("文本分析结果:" )
for key, value in result.items():
if key != "字符频率" :
print (f"{key} : {value} " )
print ("\n字符频率前 5 名:" )
sorted_chars = sorted (result["字符频率" ].items(), key=lambda x: x[1 ], reverse=True )
for char, freq in sorted_chars[:5 ]:
print (f"'{char} ': {freq} 次" )
第 6 章:面向对象编程
🏗️ 什么是面向对象? 面向对象编程就像搭积木 ,我们先设计积木的样子(类),然后用这个设计制造很多积木(对象)。
class Dog :
"""狗狗类"""
def __init__ (self, name, breed, age ):
"""初始化方法 - 创建狗狗时调用"""
self .name = name
self .breed = breed
self .age = age
self .energy = 100
def bark (self ):
"""狗狗叫"""
return f"{self.name} :汪汪汪!"
def play (self ):
"""玩耍"""
if self .energy > 20 :
self .energy -= 20
return f"{self.name} 开心地玩耍!精力剩余:{self.energy} "
else :
return f"{self.name} 太累了,需要休息"
def sleep (self ):
"""睡觉恢复精力"""
self .energy = min (100 , self .energy + 50 )
return f"{self.name} 睡了一觉,精力恢复到:{self.energy} "
my_dog = Dog("小白" , "金毛" , 3 )
friend_dog = Dog("小黑" , "拉布拉多" , 2 )
print (my_dog.bark())
print (my_dog.play())
print (my_dog.play())
print (my_dog.sleep())
🎯 类的基本概念 class Student :
"""学生类示例"""
school_name = "Python 学院"
student_count = 0
def __init__ (self, name, student_id, major ):
"""构造方法"""
self .name = name
self .student_id = student_id
self .major = major
self .courses = []
self .gpa = 0.0
Student.student_count += 1
def add_course (self, course_name, score ):
"""添加课程"""
self .courses.append({"course" : course_name, "score" : score})
self ._calculate_gpa()
def _calculate_gpa (self ):
"""计算 GPA(私有方法)"""
if self .courses:
total_score = sum (course["score" ] for course in self .courses)
self .gpa = total_score / len (self .courses)
def get_info (self ):
"""获取学生信息"""
info = f"姓名:{self.name} \n"
info += f"学号:{self.student_id} \n"
info += f"专业:{self.major} \n"
info += f"GPA:{self.gpa:.2 f} \n"
info += f"学校:{Student.school_name} "
return info
@classmethod
def get_student_count (cls ):
"""类方法 - 获取学生总数"""
return cls.student_count
@staticmethod
def is_passing_grade (score ):
"""静态方法 - 判断是否及格"""
return score >= 60
student1 = Student("小明" , "2023001" , "计算机科学" )
student2 = Student("小红" , "2023002" , "数据科学" )
student1.add_course("Python 编程" , 95 )
student1.add_course("数据结构" , 88 )
print (student1.get_info())
print (f"\n学生总数:{Student.get_student_count()} " )
print (f"95 分是否及格:{Student.is_passing_grade(95 )} " )
🧬 继承 - 代码的遗传
class Animal :
"""动物基类"""
def __init__ (self, name, species ):
self .name = name
self .species = species
self .energy = 100
def eat (self ):
self .energy = min (100 , self .energy + 20 )
return f"{self.name} 吃饱了,精力:{self.energy} "
def sleep (self ):
self .energy = 100
return f"{self.name} 睡了一觉,精力恢复满了"
def make_sound (self ):
return f"{self.name} 发出了声音"
class Cat (Animal ):
"""猫类 - 继承自动物类"""
def __init__ (self, name, breed ):
super ().__init__(name, "猫" )
self .breed = breed
def make_sound (self ):
return f"{self.name} :喵喵喵~"
def climb_tree (self ):
if self .energy > 30 :
self .energy -= 30
return f"{self.name} 爬上了树!"
else :
return f"{self.name} 太累了,爬不动树"
class Dog (Animal ):
"""狗类 - 继承自动物类"""
def __init__ (self, name, breed ):
super ().__init__(name, "狗" )
self .breed = breed
def make_sound (self ):
return f"{self.name} :汪汪汪!"
def fetch_ball (self ):
if self .energy > 25 :
self .energy -= 25
return f"{self.name} 捡回了球!"
else :
return f"{self.name} 太累了,不想捡球"
my_cat = Cat("小咪" , "波斯猫" )
my_dog = Dog("小汪" , "金毛" )
print (my_cat.make_sound())
print (my_cat.climb_tree())
print (my_cat.eat())
print (my_dog.make_sound())
print (my_dog.fetch_ball())
🎭 多态 - 同样的动作,不同的表现
def animal_concert (animals ):
"""动物音乐会 - 展示多态"""
print ("🎵 动物音乐会开始了!" )
for animal in animals:
print (f" {animal.make_sound()} " )
animals = [
Cat("小咪" , "波斯猫" ),
Dog("小汪" , "金毛" ),
Cat("小花" , "英短" ),
Dog("小黑" , "拉布拉多" )
]
animal_concert(animals)
🔒 封装 - 保护数据 class BankAccount :
"""银行账户类 - 演示封装"""
def __init__ (self, account_number, initial_balance=0 ):
self .account_number = account_number
self .__balance = initial_balance
self .__transaction_history = []
def deposit (self, amount ):
"""存款"""
if amount > 0 :
self .__balance += amount
self .__add_transaction("存款" , amount)
return f"存款成功!当前余额:¥{self.__balance} "
else :
return "存款金额必须大于 0"
def withdraw (self, amount ):
"""取款"""
if amount <= 0 :
return "取款金额必须大于 0"
elif amount > self .__balance:
return "余额不足"
else :
self .__balance -= amount
self .__add_transaction("取款" , amount)
return f"取款成功!当前余额:¥{self.__balance} "
def get_balance (self ):
"""获取余额(只读)"""
return self .__balance
def __add_transaction (self, transaction_type, amount ):
"""私有方法 - 添加交易记录"""
import datetime
self .__transaction_history.append({
"type" : transaction_type,
"amount" : amount,
"time" : datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )
})
def get_transaction_history (self ):
"""获取交易历史"""
return self .__transaction_history.copy()
account = BankAccount("123456789" , 1000 )
print (account.deposit(500 ))
print (account.withdraw(200 ))
print (f"当前余额:¥{account.get_balance()} " )
for transaction in account.get_transaction_history():
print (f"{transaction['time' ]} : {transaction['type' ]} ¥{transaction['amount' ]} " )
✅ 第 6 章练习 class Book :
"""图书类"""
def __init__ (self, title, author, isbn, copies=1 ):
self .title = title
self .author = author
self .isbn = isbn
self .total_copies = copies
self .available_copies = copies
self .borrowed_by = []
def borrow (self, borrower_name ):
"""借书"""
if self .available_copies > 0 :
self .available_copies -= 1
self .borrowed_by.append(borrower_name)
return f"《{self.title} 》借阅成功!"
else :
return f"《{self.title} 》暂无库存"
def return_book (self, borrower_name ):
"""还书"""
if borrower_name in self .borrowed_by:
self .available_copies += 1
self .borrowed_by.remove(borrower_name)
return f"《{self.title} 》归还成功!"
else :
return "还书信息有误"
def get_info (self ):
"""获取图书信息"""
return f"《{self.title} 》- {self.author} (可借:{self.available_copies} /{self.total_copies} )"
class Library :
"""图书馆类"""
def __init__ (self, name ):
self .name = name
self .books = {}
def add_book (self, book ):
"""添加图书"""
if book.isbn in self .books:
self .books[book.isbn].total_copies += book.total_copies
self .books[book.isbn].available_copies += book.available_copies
else :
self .books[book.isbn] = book
return f"图书《{book.title} 》添加成功"
def search_book (self, keyword ):
"""搜索图书"""
results = []
for book in self .books.values():
if keyword.lower() in book.title.lower() or keyword.lower() in book.author.lower():
results.append(book)
return results
def list_all_books (self ):
"""列出所有图书"""
if not self .books:
return "图书馆暂无图书"
book_list = f"\n=== {self.name} 图书列表 ===\n"
for book in self .books.values():
book_list += book.get_info() + "\n"
return book_list
library = Library("Python 学习图书馆" )
books = [
Book("Python 编程入门" , "张三" , "978-1-1111-1111-1" , 3 ),
Book("数据结构与算法" , "李四" , "978-2-2222-2222-2" , 2 ),
Book("机器学习实战" , "王五" , "978-3-3333-3333-3" , 1 )
]
for book in books:
print (library.add_book(book))
print (library.list_all_books())
python_book = library.books["978-1-1111-1111-1" ]
print (python_book.borrow("小明" ))
print (python_book.borrow("小红" ))
print (python_book.return_book("小明" ))
第 7 章:模块和包
📦 什么是模块? 模块就像工具箱 ,里面装着各种有用的工具(函数和类)。
import math
print (f"圆周率:{math.pi} " )
print (f"平方根:{math.sqrt(16 )} " )
from random import randint, choice
print (f"随机数:{randint(1 , 10 )} " )
print (f"随机选择:{choice(['苹果' , '香蕉' , '橙子' ])} " )
import datetime as dt
now = dt.datetime.now()
print (f"现在时间:{now.strftime('%Y-%m-%d %H:%M:%S' )} " )
🛠️ 创建自己的模块 """
我的工具模块
包含一些常用的工具函数
"""
def greet (name, language="中文" ):
"""多语言问候函数"""
greetings = {
"中文" : f"你好,{name} !" ,
"英文" : f"Hello, {name} !" ,
"日文" : f"こんにちは、{name} !" ,
"韩文" : f"안녕하세요, {name} !"
}
return greetings.get(language, f"Hello, {name} !" )
def calculate_bmi (weight, height ):
"""计算 BMI 指数"""
bmi = weight / (height ** 2 )
if bmi < 18.5 :
category = "偏瘦"
elif bmi < 24 :
category = "正常"
elif bmi < 28 :
category = "偏胖"
else :
category = "肥胖"
return {"bmi" : round (bmi, 2 ), "category" : category}
class SimpleCalculator :
"""简单计算器类"""
@staticmethod
def add (a, b ):
return a + b
@staticmethod
def multiply (a, b ):
return a * b
VERSION = "1.0.0"
AUTHOR = "Python 学习者"
if __name__ == "__main__" :
print ("这是我的工具模块" )
print (f"版本:{VERSION} " )
print (f"作者:{AUTHOR} " )
import my_utils
print (my_utils.greet("小明" ))
print (my_utils.greet("Tom" , "英文" ))
calc = my_utils.SimpleCalculator()
print (f"3 + 5 = {calc.add(3 , 5 )} " )
print (f"模块版本:{my_utils.VERSION} " )
bmi_result = my_utils.calculate_bmi(70 , 1.75 )
print (f"BMI: {bmi_result['bmi' ]} ({bmi_result['category' ]} )" )
📚 常用内置模块
1. os 模块 - 操作系统接口 import os
print (f"当前目录:{os.getcwd()} " )
print (f"目录内容:{os.listdir('.' )} " )
if os.path.exists("my_file.txt" ):
print ("文件存在" )
else :
print ("文件不存在" )
if not os.path.exists("test_folder" ):
os.makedirs("test_folder" )
print ("目录创建成功" )
2. datetime 模块 - 日期时间处理 from datetime import datetime, timedelta, date
now = datetime.now()
print (f"现在:{now} " )
formatted = now.strftime("%Y年%m月%d日 %H:%M:%S" )
print (f"格式化时间:{formatted} " )
tomorrow = now + timedelta(days=1 )
print (f"明天:{tomorrow.strftime('%Y-%m-%d' )} " )
birthday = date(2000 , 5 , 15 )
today = date.today()
age = today.year - birthday.year
print (f"年龄:{age} 岁" )
3. json 模块 - JSON 数据处理 import json
student_data = {
"name" : "小明" ,
"age" : 20 ,
"courses" : ["Python" , "数学" , "英语" ],
"is_active" : True
}
json_string = json.dumps(student_data, ensure_ascii=False , indent=2 )
print ("JSON 字符串:" )
print (json_string)
parsed_data = json.loads(json_string)
print (f"\n解析后的姓名:{parsed_data['name' ]} " )
with open ("student.json" , "w" , encoding="utf-8" ) as f:
json.dump(student_data, f, ensure_ascii=False , indent=2 )
with open ("student.json" , "r" , encoding="utf-8" ) as f:
loaded_data = json.load(f)
print (f"从文件读取的数据:{loaded_data} " )
第 8 章:文件操作
📁 文件读写基础
def write_diary (content ):
"""写日记"""
from datetime import datetime
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S" )
diary_entry = f"[{timestamp} ] {content} \n"
with open ("diary.txt" , "a" , encoding="utf-8" ) as f:
f.write(diary_entry)
print ("日记写入成功!" )
def read_diary ():
"""读取日记"""
try :
with open ("diary.txt" , "r" , encoding="utf-8" ) as f:
content = f.read()
if content:
print ("=== 我的日记 ===" )
print (content)
else :
print ("日记本是空的" )
except FileNotFoundError:
print ("还没有日记文件,开始写第一篇日记吧!" )
write_diary("今天学习了 Python 文件操作,很有趣!" )
write_diary("明天要继续学习异常处理" )
read_diary()
📊 CSV 文件处理 import csv
def save_students_csv (students ):
"""保存学生数据到 CSV 文件"""
with open ("students.csv" , "w" , newline="" , encoding="utf-8" ) as f:
writer = csv.writer(f)
writer.writerow(["姓名" , "年龄" , "专业" , "成绩" ])
for student in students:
writer.writerow([
student["name" ],
student["age" ],
student["major" ],
student["score" ]
])
print ("学生数据保存成功!" )
def read_students_csv ():
"""从 CSV 文件读取学生数据"""
students = []
try :
with open ("students.csv" , "r" , encoding="utf-8" ) as f:
reader = csv.DictReader(f)
for row in reader:
students.append({
"name" : row["姓名" ],
"age" : int (row["年龄" ]),
"major" : row["专业" ],
"score" : float (row["成绩" ])
})
return students
except FileNotFoundError:
print ("CSV 文件不存在" )
return []
sample_students = [
{"name" : "小明" , "age" : 20 , "major" : "计算机" , "score" : 85.5 },
{"name" : "小红" , "age" : 19 , "major" : "数学" , "score" : 92.0 },
{"name" : "小刚" , "age" : 21 , "major" : "物理" , "score" : 78.5 }
]
save_students_csv(sample_students)
loaded_students = read_students_csv()
print ("读取的学生数据:" )
for student in loaded_students:
print (f"{student['name' ]} - {student['major' ]} - {student['score' ]} " )
第 9 章:异常处理
⚠️ 什么是异常? 异常就像生活中的意外情况 ,我们需要提前准备应对方案。
def safe_divide (a, b ):
"""安全的除法运算"""
try :
result = a / b
return f"{a} ÷ {b} = {result} "
except ZeroDivisionError:
return "错误:不能除以零!"
except TypeError:
return "错误:请输入数字!"
except Exception as e:
return f"未知错误:{e} "
else :
print ("计算成功完成" )
finally :
print ("除法运算结束" )
print (safe_divide(10 , 2 ))
print (safe_divide(10 , 0 ))
print (safe_divide(10 , "a" ))
🎯 实际应用:文件处理异常 def safe_file_reader (filename ):
"""安全的文件读取器"""
try :
with open (filename, "r" , encoding="utf-8" ) as f:
content = f.read()
return content
except FileNotFoundError:
print (f"错误:文件 '{filename} ' 不存在" )
return None
except PermissionError:
print (f"错误:没有权限读取文件 '{filename} '" )
return None
except UnicodeDecodeError:
print (f"错误:文件 '{filename} ' 编码格式不正确" )
return None
except Exception as e:
print (f"读取文件时发生未知错误:{e} " )
return None
class InvalidAgeError (Exception ):
"""年龄无效异常"""
def __init__ (self, age, message="年龄必须在 0-150 之间" ):
self .age = age
self .message = message
super ().__init__(self .message)
def validate_age (age ):
"""验证年龄"""
if not isinstance (age, int ):
raise TypeError("年龄必须是整数" )
if age < 0 or age > 150 :
raise InvalidAgeError(age)
return True
try :
validate_age(200 )
except InvalidAgeError as e:
print (f"年龄验证失败:{e.message} ,输入的年龄是:{e.age} " )
except TypeError as e:
print (f"类型错误:{e} " )
实战项目
🎮 项目 1:个人任务管理器 import json
import datetime
class TaskManager :
"""个人任务管理器"""
def __init__ (self, filename="tasks.json" ):
self .filename = filename
self .tasks = self .load_tasks()
def load_tasks (self ):
"""加载任务"""
try :
with open (self .filename, "r" , encoding="utf-8" ) as f:
return json.load(f)
except FileNotFoundError:
return []
def save_tasks (self ):
"""保存任务"""
with open (self .filename, "w" , encoding="utf-8" ) as f:
json.dump(self .tasks, f, ensure_ascii=False , indent=2 )
def add_task (self, title, description="" , priority="中" ):
"""添加任务"""
task = {
"id" : len (self .tasks) + 1 ,
"title" : title,
"description" : description,
"priority" : priority,
"status" : "待完成" ,
"created_at" : datetime.datetime.now().isoformat(),
"completed_at" : None
}
self .tasks.append(task)
self .save_tasks()
return f"任务 '{title} ' 添加成功!"
def complete_task (self, task_id ):
"""完成任务"""
for task in self .tasks:
if task["id" ] == task_id:
task["status" ] = "已完成"
task["completed_at" ] = datetime.datetime.now().isoformat()
self .save_tasks()
return f"任务 '{task['title' ]} ' 已完成!"
return "任务不存在!"
def list_tasks (self, status=None ):
"""列出任务"""
filtered_tasks = self .tasks
if status:
filtered_tasks = [t for t in self .tasks if t["status" ] == status]
if not filtered_tasks:
return "没有任务"
result = "\n=== 任务列表 ===\n"
for task in filtered_tasks:
result += f"[{task['id' ]} ] {task['title' ]} - {task['status' ]} ({task['priority' ]} )\n"
if task['description' ]:
result += f" 描述:{task['description' ]} \n"
return result
def delete_task (self, task_id ):
"""删除任务"""
for i, task in enumerate (self .tasks):
if task["id" ] == task_id:
deleted_task = self .tasks.pop(i)
self .save_tasks()
return f"任务 '{deleted_task['title' ]} ' 已删除!"
return "任务不存在!"
def main ():
"""主程序"""
tm = TaskManager()
while True :
print ("\n=== 个人任务管理器 ===" )
print ("1. 添加任务" )
print ("2. 查看所有任务" )
print ("3. 查看待完成任务" )
print ("4. 完成任务" )
print ("5. 删除任务" )
print ("6. 退出" )
choice = input ("请选择操作(1-6):" )
if choice == "1" :
title = input ("任务标题:" )
description = input ("任务描述(可选):" )
priority = input ("优先级(高/中/低,默认中):" ) or "中"
print (tm.add_task(title, description, priority))
elif choice == "2" :
print (tm.list_tasks())
elif choice == "3" :
print (tm.list_tasks("待完成" ))
elif choice == "4" :
print (tm.list_tasks("待完成" ))
try :
task_id = int (input ("请输入要完成的任务 ID:" ))
print (tm.complete_task(task_id))
except ValueError:
print ("请输入有效的任务 ID!" )
elif choice == "5" :
print (tm.list_tasks())
try :
task_id = int (input ("请输入要删除的任务 ID:" ))
print (tm.delete_task(task_id))
except ValueError:
print ("请输入有效的任务 ID!" )
elif choice == "6" :
print ("再见!" )
break
else :
print ("无效选择,请重新输入!" )
if __name__ == "__main__" :
main()
🎓 学习总结与建议
📈 学习进度检查表
第 1 章 :能够安装 Python 并运行第一个程序
第 2 章 :掌握变量、运算符、输入输出
第 3 章 :熟练使用各种数据类型
第 4 章 :能够使用条件语句和循环
第 5 章 :能够定义和使用函数
第 6 章 :理解面向对象编程概念
第 7 章 :能够使用和创建模块
第 8 章 :掌握文件操作
第 9 章 :能够处理异常
实战项目 :完成至少一个完整项目
💡 学习建议
循序渐进 :不要急于求成,每个概念都要理解透彻
多动手练习 :编程是实践性很强的技能
阅读他人代码 :学习优秀的编程风格
做项目 :通过实际项目巩固知识
加入社区 :与其他学习者交流经验
🚀 下一步学习方向
Web 开发 :学习 Django 或 Flask 框架
数据科学 :学习 Pandas、NumPy、Matplotlib
人工智能 :学习 TensorFlow 或 PyTorch
自动化 :学习 Selenium、requests 等库
游戏开发 :学习 Pygame
📚 推荐资源
官方文档 :Python.org
在线练习 :LeetCode、HackerRank
开源项目 :GitHub 上的 Python 项目
社区论坛 :Stack Overflow、Python 中文社区
🎉 恭喜你完成了 Python 基础学习!
记住:编程是一门实践的艺术,只有不断练习才能真正掌握。
现在开始你的 Python 编程之旅吧!🐍✨
相关免费在线工具 加密/解密文本 使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
Mermaid 预览与可视化编辑 基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
随机西班牙地址生成器 随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
Gemini 图片去水印 基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
curl 转代码 解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online