跳到主要内容
Python 基础语法指南 | 极客日志
Python AI 算法
Python 基础语法指南 Python 编程的基础知识,涵盖编程概念、Python 特点、基础语法(变量、数据类型、运算符)、控制结构(条件、循环)、数据结构(列表、元组、字典、集合)、函数与模块以及面向对象编程(类、对象、封装、继承、多态)。内容包含大量代码示例和实用技巧,适合初学者系统学习 Python 基础语法与核心概念。
灵魂伴侣 发布于 2026/3/29 更新于 2026/5/29 27 浏览前言
1. 什么是编程?
编程 就像是教电脑做事 的过程。想象你有一个非常听话但很笨的助手,你需要用它能理解的语言(编程语言)一步一步地告诉它该做什么。
你 = 程序员(下达指令的人)
Python = 你和电脑沟通的语言
电脑 = 执行指令的助手
2. Python 的特点
Python 之所以适合初学者,是因为它:
像英语一样易读 - 代码看起来像自然语言
简洁明了 - 用很少的代码完成很多功能
功能强大 - 从简单计算到人工智能都能做
免费开源 - 任何人都可以免费使用
3. 程序的基本结构
一个 Python 程序就像做菜的食谱 :
准备材料(定义变量)
处理材料(执行操作)
呈现结果(输出信息)
1. Python 基础语法
1.1 变量与数据类型
什么是变量?
想象一下,变量就像是一个贴了标签的储物盒 。你可以在盒子里存放不同的东西,通过标签来找到它。
变量名 = 标签名
变量值 = 盒子里的东西
赋值操作 = 把东西放进盒子并贴上标签
name = "小明"
age = 18
height = 1.75
is_student = True
print (name)
print (age)
name = "小红"
print (name)
数据类型:数据的分类
就像物品有不同的类别(食物、衣服、工具),python 中的数据也有不同的类型:
整数 (int) - 像数苹果的个数,没有小数
浮点数 (float) - 像量身高,有小数
字符串 (str) - 像写文字,用引号包围
布尔值 (bool) - 像判断题,只有对/错
student_count = 45
age = 18
price = 19.99
pi = 3.14159
name = "李华"
message = '他说:"你好!"'
is_raining = True
has_homework = False
print (type (age))
print (type (price))
print (type (name))
print (type (is_raining))
类型转换:改变物品的包装
text_number = "123"
real_number = int (text_number)
print (real_number)
print (type (real_number))
score = 95
score_text = str (score)
print ("我的分数是:" + score_text)
price = 19.99
whole_price = int (price)
print (whole_price)
1.2 运算符与表达式
算术运算符:数学计算 Python 可以做各种数学运算,就像计算器一样:
算术运算 :加减乘除
比较运算 :比较大小
逻辑运算 :组合条件
a = 10
b = 3
print (a + b)
print (a - b)
print (a * b)
print (a / b)
print (a // b)
print (a % b)
print (a ** b)
比较运算符:比较大小 x = 10
y = 5
print (x == y)
print (x != y)
print (x > y)
print (x < y)
print (x >= y)
print (x <= y)
逻辑运算符:组合条件
is_weekend = True
has_money = True
can_shopping = is_weekend and has_money
print (can_shopping)
is_holiday = False
is_weekend = True
can_rest = is_holiday or is_weekend
print (can_rest)
is_raining = True
can_play_outside = not is_raining
print (can_play_outside)
1.3 输入与输出
输入 :你告诉程序信息(像回答问题)
输出 :程序告诉你结果(像程序说话)
获取用户输入:和程序对话
name = input ("请输入你的名字:" )
age = input ("请输入你的年龄:" )
print ("你好," + name + "!" )
print ("你今年" + age + "岁了" )
输出信息:程序告诉你结果
print ("Hello, World!" )
name = "小明"
score = 95
print ("学生:" , name, "分数:" , score)
print (f"学生:{name} ,分数:{score} " )
price = 19.99
quantity = 3
total = price * quantity
print (f"单价:{price} 元,数量:{quantity} ,总价:{total:.2 f} 元" )
2. Python 控制结构
2.1 条件语句:让程序做决定
如果 下雨,就 带伞
否则如果 阴天,就 带外套
否则 ,什么都不带
if 语句 - 最基本的条件判断 age = 18
if age >= 18 :
print ("你已经成年了!" )
print ("可以考驾照了" )
age = 16
if age >= 18 :
print ("成年" )
else :
print ("未成年" )
if-elif-else 语句 - 多条件判断 score = 85
if score >= 90 :
print ("优秀" )
elif score >= 80 :
print ("良好" )
elif score >= 70 :
print ("中等" )
elif score >= 60 :
print ("及格" )
else :
print ("不及格" )
嵌套条件 - 条件中的条件 age = 20
has_license = True
has_car = False
if age >= 18 :
if has_license:
if has_car:
print ("可以开车出门" )
else :
print ("有驾照但没车" )
else :
print ("需要先考驾照" )
else :
print ("年龄不够,不能开车" )
2.2 循环语句:重复执行任务
for 循环 :知道要重复多少次(像数 1 到 10)
while 循环 :不知道要重复多少次,直到条件满足(像猜密码直到正确)
while 循环 - 当条件满足时重复执行
count = 0
while count < 5 :
print (f"这是第{count + 1 } 次循环" )
count += 1
password = ""
while password != "123456" :
password = input ("请输入密码:" )
print ("密码正确!" )
for 循环 - 遍历序列中的每个元素
fruits = ["苹果" , "香蕉" , "橙子" , "草莓" ]
for fruit in fruits:
print (f"我喜欢吃{fruit} " )
name = "Python"
for char in name:
print (char)
range() 函数 - 生成数字序列
for i in range (5 ):
print (i)
for i in range (2 , 6 ):
print (i)
for i in range (1 , 11 , 2 ):
print (i)
循环控制语句
print ("break 示例:" )
for i in range (10 ):
if i == 5 :
break
print (i)
print ("continue 示例:" )
for i in range (10 ):
if i % 2 == 0 :
continue
print (i)
3. Python 数据结构
3.1 列表 (List) - 有序的可变序列
列表的基本概念 列表就像是一个动态的购物车 或者可编辑的任务清单 ,可以存放多个物品。
有序 :每个元素都有固定的位置
可变 :可以随时添加、删除、修改元素
可重复 :允许包含重复的元素
混合类型 :可以存放不同类型的数据
empty_list = []
shopping_list = ["苹果" , "牛奶" , "面包" ]
numbers = [1 , 2 , 3 , 4 , 5 ]
mixed_list = [1 , "苹果" , 3.14 , True ]
nested_list = [[1 , 2 ], [3 , 4 ], [5 , 6 ]]
print (f"购物清单:{shopping_list} " )
print (f"混合列表:{mixed_list} " )
print (f"嵌套列表:{nested_list} " )
列表的索引和切片详解
索引 索引就像门牌号 或者座位号 ,用来精确定位列表中的每个元素。
正索引 :从前往后编号,从 0 开始
负索引 :从后往前编号,从 -1 开始
fruits = ["苹果" , "香蕉" , "橙子" , "草莓" , "葡萄" , "芒果" ]
print ("列表:" , fruits)
print ("长度:" , len (fruits))
print ("\n=== 正索引 ===" )
print (f"fruits[0] = {fruits[0 ]} " )
print (f"fruits[1] = {fruits[1 ]} " )
print (f"fruits[2] = {fruits[2 ]} " )
print (f"fruits[3] = {fruits[3 ]} " )
print ("\n=== 负索引 ===" )
print (f"fruits[-1] = {fruits[-1 ]} " )
print (f"fruits[-2] = {fruits[-2 ]} " )
print (f"fruits[-3] = {fruits[-3 ]} " )
索引的可视化理解
列表:["苹果", "香蕉", "橙子", "草莓", "葡萄", "芒果"]
正索引:0 1 2 3 4 5
负索引:-6 -5 -4 -3 -2 -1
切片 numbers = [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
print ("原始列表:" , numbers)
print ("\n=== 基本切片 ===" )
print (f"numbers[2:6] = {numbers[2 :6 ]} " )
print (f"numbers[:4] = {numbers[:4 ]} " )
print (f"numbers[5:] = {numbers[5 :]} " )
print (f"numbers[:] = {numbers[:]} " )
参数 含义 默认值 示例 start开始位置(包含) 0 [2:] 从索引 2 开始stop结束位置(不包含) 列表长度 [:5] 到索引 5 结束step步长(每隔几个取一个) 1 [::2] 每隔一个取一个
访问列表元素 fruits = ["苹果" , "香蕉" , "橙子" , "草莓" ]
print (fruits[0 ])
print (fruits[1 ])
print (fruits[-1 ])
print (fruits[-2 ])
print (fruits[1 :3 ])
print (fruits[:2 ])
print (fruits[::2 ])
修改列表 fruits = ["苹果" , "香蕉" ]
fruits.append("橙子" )
print (fruits)
fruits.extend(["草莓" , "葡萄" ])
print (fruits)
fruits.insert(1 , "梨" )
print (fruits)
more_fruits = ["芒果" , "菠萝" ]
all_fruits = fruits + more_fruits
print (all_fruits)
fruits = ["苹果" , "梨" , "香蕉" , "橙子" , "梨" , "草莓" ]
del fruits[1 ]
print (fruits)
removed_fruit = fruits.pop(2 )
print (f"删除了:{removed_fruit} " )
print (fruits)
fruits.remove("梨" )
print (fruits)
fruits.clear()
print (fruits)
fruits = ["苹果" , "香蕉" , "橙子" ]
fruits[1 ] = "葡萄"
print (fruits)
fruits[0 :2 ] = ["芒果" , "菠萝" ]
print (fruits)
fruits[1 :1 ] = ["西瓜" , "哈密瓜" ]
print (fruits)
列表的查询和统计 numbers = [1 , 3 , 5 , 3 , 7 , 9 , 3 , 1 ]
print (len (numbers))
print (numbers.count(3 ))
print (numbers.count(1 ))
print (numbers.index(5 ))
print (numbers.index(3 ))
print (numbers.index(3 , 2 ))
print (5 in numbers)
print (10 in numbers)
3.2 元组 (Tuple) - 有序的不可变序列 元组就像是一个固定的清单、密封的档案袋 或者不可修改的合同 ,一旦创建就不能修改。适合存放不应该改变的数据。
有序 :元素有固定位置
不可变 :创建后不能修改
可重复 :允许重复元素
通常用于存储相关数据 :如坐标、配置信息等
colors = ("红色" , "绿色" , "蓝色" )
coordinates = (10 , 20 )
print (colors[0 ])
student_info = ("张三" , 18 , "清华大学" )
name, age, school = student_info
print (f"{name} 今年{age} 岁,在{school} 上学" )
3.3 字典 (Dict) - 键值对集合 字典就像是一个通讯录 或者词典 ,通过"键"(如名字)快速找到对应的"值"(如电话号码)。
键值对 :每个元素由键 (key) 和值 (value) 组成
无序 :Python 3.7+ 保持插入顺序,但本质上无序
键必须唯一 :不能有重复的键
键必须是不可变类型 :字符串、数字、元组等
值可以是任意类型 :包括列表、字典等
contacts = {
"张三" : "13800138000" ,
"李四" : "13900139000" ,
"王五" : "13700137000"
}
print (contacts["张三" ])
contacts["赵六" ] = "13600136000"
contacts["张三" ] = "13800138001"
del contacts["李四" ]
print (contacts)
字典的常用方法 student = {"name" : "小明" , "age" : 18 , "score" : 95 }
print ("name" in student)
print ("address" in student)
print (student.get("name" ))
print (student.get("address" ))
print (student.get("address" , "未知" ))
print (student.keys())
print (student.values())
3.4 集合 (Set) - 无序的唯一元素集合 集合就像是一个没有重复项目的袋子 ,自动去除重复,而且不关心顺序。
无序 :元素没有固定顺序
唯一 :自动去除重复元素
可变 :可以添加、删除元素
只能包含不可变类型 :数字、字符串、元组等
fruits = {"苹果" , "香蕉" , "橙子" , "苹果" }
print (fruits)
set1 = {1 , 2 , 3 , 4 , 5 }
set2 = {4 , 5 , 6 , 7 , 8 }
print (set1 | set2)
print (set1 & set2)
print (set1 - set2)
print (set1 ^ set2)
4. Python 函数和模块
4.1 函数基础
什么是函数? 函数就像是一个预制工具 或者食谱 - 你定义一次制作方法,之后可以多次使用。
定义函数 = 设计电器的功能或建立生产线
调用函数 = 使用电器或启动生产线
参数 = 给电器提供原料或给生产线提供材料
返回值 = 电器产出的成品或生产线的最终产品
def make_tea (tea_type, sugar_level=1 ):
"""泡茶函数
参数:
tea_type: 茶叶类型
sugar_level: 糖度级别 (1-5)
返回:
泡好的茶描述
"""
tea_description = f"一杯{tea_type} 茶"
if sugar_level > 1 :
tea_description += f",糖度{sugar_level} 级"
return tea_description
tea1 = make_tea("绿茶" )
tea2 = make_tea("红茶" , 3 )
tea3 = make_tea(sugar_level=5 , tea_type="乌龙茶" )
print (tea1)
print (tea2)
print (tea3)
函数参数:给工具提供材料 def create_student_info (name, age, grade ):
"""创建学生信息 - 参数必须按顺序传递"""
return f"姓名:{name} ,年龄:{age} ,年级:{grade} "
info1 = create_student_info("小明" , 15 , "九年级" )
print (info1)
info2 = create_student_info(15 , "小明" , "九年级" )
print (info2)
def order_coffee (coffee_type, size="中杯" , sugar=True , ice=False ):
"""订购咖啡 - 带有默认参数"""
order = f"{size} {coffee_type} "
if sugar:
order += ",加糖"
else :
order += ",无糖"
if ice:
order += ",加冰"
else :
order += ",热饮"
return order
order1 = order_coffee("拿铁" )
order2 = order_coffee("美式" , "大杯" )
order3 = order_coffee("卡布奇诺" , sugar=False )
order4 = order_coffee("摩卡" , "小杯" , True , True )
print (order1)
print (order2)
print (order3)
print (order4)
def build_computer (cpu, memory, storage, gpu="集成显卡" , monitor=24 ):
"""组装电脑 - 使用关键字参数更清晰"""
return f"CPU: {cpu} , 内存:{memory} G, 硬盘:{storage} G, 显卡:{gpu} , 显示器:{monitor} 寸"
computer1 = build_computer(cpu="i7" , memory=16 , storage=512 )
computer2 = build_computer(memory=32 , storage=1000 , cpu="i9" , gpu="RTX 4080" )
computer3 = build_computer("i5" , 8 , 256 , monitor=27 )
print (computer1)
print (computer2)
print (computer3)
def make_smoothie (*fruits, **extras ):
"""制作果汁 - 接受任意数量的水果和额外选项"""
smoothie = "混合果汁包含:"
smoothie += "、" .join(fruits)
if extras:
smoothie += ",额外添加:"
for item, amount in extras.items():
smoothie += f"{item} {amount} 份、"
smoothie = smoothie.rstrip("、" )
return smoothie
smoothie1 = make_smoothie("香蕉" , "草莓" )
smoothie2 = make_smoothie("芒果" , "菠萝" , "椰子" , ice=2 , sugar=1 )
smoothie3 = make_smoothie("苹果" , yogurt=1 , honey=1 )
print (smoothie1)
print (smoothie2)
print (smoothie3)
返回值:工具给出的结果
def calculate_bmi (weight, height ):
"""计算 BMI 指数"""
bmi = weight / (height ** 2 )
return round (bmi, 2 )
def analyze_scores (scores ):
"""分析成绩数据"""
average = sum (scores) / len (scores)
highest = max (scores)
lowest = min (scores)
count = len (scores)
return average, highest, lowest, count
def get_student_report (name, scores ):
"""生成学生报告"""
average = sum (scores) / len (scores)
grade = "优秀" if average >= 90 else "良好" if average >= 80 else "及格"
return {
"姓名" : name,
"平均分" : round (average, 2 ),
"最高分" : max (scores),
"最低分" : min (scores),
"等级" : grade
}
bmi = calculate_bmi(70 , 1.75 )
print (f"BMI 指数:{bmi} " )
avg, high, low, cnt = analyze_scores([85 , 92 , 78 , 96 , 88 ])
print (f"平均分:{avg} , 最高分:{high} , 最低分:{low} , 人数:{cnt} " )
report = get_student_report("小明" , [85 , 92 , 78 , 96 , 88 ])
print (f"学生报告:{report} " )
函数的文档字符串 def calculate_compound_interest (principal, rate, years, compound_frequency=1 ):
"""计算复利
参数:
principal (float): 本金
rate (float): 年利率 (例如 0.05 表示 5%)
years (int): 投资年数
compound_frequency (int): 复利计算频率 (1=年,12=月)
返回:
tuple: (最终金额,总收益)
示例:
>>> calculate_compound_interest(1000, 0.05, 10)
(1628.89, 628.89)
"""
final_amount = principal * (1 + rate/compound_frequency) ** (compound_frequency * years)
total_earnings = final_amount - principal
return round (final_amount, 2 ), round (total_earnings, 2 )
print (calculate_compound_interest.__doc__)
result = calculate_compound_interest(1000 , 0.05 , 10 )
print (f"最终金额:{result[0 ]} , 总收益:{result[1 ]} " )
4.2 变量作用域:变量的可见范围
school_name = "第一中学"
student_count = 0
def register_student (name, grade ):
"""注册学生 - 演示局部变量和全局变量"""
student_id = f"{grade} _{name} "
classroom = f"{grade} 班"
print (f"{name} 在 {school_name} {classroom} 注册" )
global student_count
student_count += 1
return student_id, classroom
def create_student_profile (name, age ):
"""创建学生档案 - 嵌套函数演示"""
profile_id = f"STU{age:03d} "
def generate_email ():
"""内层函数 - 可以访问外层函数的变量"""
email = f"{name} @{school_name} .edu.cn"
return email.lower()
email = generate_email()
return {
"id" : profile_id,
"name" : name,
"email" : email,
"school" : school_name
}
id1, class1 = register_student("小明" , "九年级" )
id2, class2 = register_student("小红" , "八年级" )
print (f"学生 ID: {id1} , 班级:{class1} " )
print (f"学生 ID: {id2} , 班级:{class2} " )
print (f"总共注册了 {student_count} 名学生" )
profile = create_student_profile("张三" , 15 )
print (f"学生档案:{profile} " )
def counter_factory ():
"""计数器工厂 - 演示 nonlocal 使用"""
count = 0
def increment ():
"""内层计数器"""
nonlocal count
count += 1
return count
def reset ():
"""重置计数器"""
nonlocal count
count = 0
return count
def get_count ():
"""获取当前计数"""
return count
return increment, reset, get_count
inc, reset, get = counter_factory()
print (inc())
print (inc())
print (inc())
print (f"当前计数:{get()} " )
reset()
print (f"重置后计数:{get()} " )
4.3 匿名函数 (Lambda):一次性小工具
匿名函数(Lambda)
概念:匿名函数是一种不需要定义函数名的简单函数,通常用于需要一个函数作为参数的场合,或者只需要使用一次的函数。
语法:lambda 参数 1, 参数 2, ... : 表达式
特点:lambda 函数只能包含一个表达式,不能包含复杂的语句,但表达式可以很复杂(如三元运算符等)。它的计算结果就是表达式的返回值。
匿名函数就像一次性的便利贴 或临时工具 :传统函数 = 正规的工具箱(有名称,可重复使用)Lambda 函数 = 一次性的便签纸(用完即弃,临时使用)
def square (x ):
return x * x
square = lambda x: x * x
print (square(5 ))
4.4 模块:工具库
概念:模块是一个包含 Python 代码的文件,它可以包含函数、类、变量等。我们可以将代码按功能组织到不同的模块中,以便于重用和维护。
导入方式:有多种导入方式,可以根据需要选择。
模块系统就像乐高积木 :模块 = 一盒特定的乐高积木导入模块 = 打开乐高盒子使用函数 = 使用特定的积木块标准库 = 官方提供的乐高套装第三方库 = 其他公司制作的乐高扩展包
Python 模块导入的 6 种方式
import math
print (f"√16 = {math.sqrt(16 )} " )
print (f"圆周率π ≈ {math.pi} " )
from math import sqrt, pi
print (f"√25 = {sqrt(25 )} " )
print (f"圆周率π ≈ {pi} " )
import math as m
from datetime import datetime as dt
print (f"√36 = {m.sqrt(36 )} " )
print (f"当前时间:{dt.now()} " )
module_name = "math"
math_module = __import__ (module_name)
print (f"动态导入的 sqrt(49) = {math_module.sqrt(49 )} " )
常用内置模块
math 模块 - 数学工具箱 import math
print ("=== Math 模块功能演示 ===" )
print (f"圆周率π: {math.pi} " )
print (f"自然常数 e: {math.e} " )
print (f"无穷大:{math.inf} " )
print (f"非数字:{math.nan} " )
print (f"\n=== 基本运算 ===" )
print (f"平方根√64: {math.sqrt(64 )} " )
print (f"绝对值|-5|: {abs (-5 )} " )
print (f"阶乘 5!: {math.factorial(5 )} " )
print (f"最大公约数 gcd(48, 18): {math.gcd(48 , 18 )} " )
print (f"最小公倍数 lcm(15, 20): {math.lcm(15 , 20 )} " )
print (f"\n=== 对数函数 ===" )
print (f"自然对数 ln(e): {math.log(math.e)} " )
print (f"以 10 为底 log10(100): {math.log10(100 )} " )
print (f"以 2 为底 log2(8): {math.log2(8 )} " )
print (f"\n=== 三角函数 ===" )
angle_degrees = 45
angle_radians = math.radians(angle_degrees)
print (f"{angle_degrees} ° = {angle_radians:.2 f} 弧度" )
print (f"sin({angle_degrees} °): {math.sin(angle_radians):.2 f} " )
print (f"cos({angle_degrees} °): {math.cos(angle_radians):.2 f} " )
print (f"tan({angle_degrees} °): {math.tan(angle_radians):.2 f} " )
print (f"\n=== 幂函数 ===" )
print (f"2 的 3 次方:{math.pow (2 , 3 )} " )
print (f"e 的 2 次方:{math.exp(2 )} " )
print (f"\n=== 取整函数 ===" )
print (f"向上取整 ceil(3.2): {math.ceil(3.2 )} " )
print (f"向下取整 floor(3.8): {math.floor(3.8 )} " )
print (f"四舍五入 round(3.5): {round (3.5 )} " )
print (f"截断小数 trunc(3.8): {math.trunc(3.8 )} " )
print (f"\n=== 角度转换 ===" )
print (f"180°转弧度:{math.radians(180 )} " )
print (f"π转角度:{math.degrees(math.pi)} " )
random 模块 - 随机数生成器 import random
import string
print ("=== Random 模块功能演示 ===" )
print (f"\n=== 基本随机 ===" )
print (f"0-1 随机小数:{random.random()} " )
print (f"1-100 随机整数:{random.randint(1 , 100 )} " )
print (f"1-10 随机整数(步长 2): {random.randrange(1 , 10 , 2 )} " )
print (f"\n=== 序列操作 ===" )
fruits = ["苹果" , "香蕉" , "橙子" , "葡萄" , "草莓" ]
print (f"随机选择一个:{random.choice(fruits)} " )
print (f"随机选择 3 个(可重复): {random.choices(fruits, k=3 )} " )
print (f"随机选择 2 个(不重复): {random.sample(fruits, 2 )} " )
random.shuffle(fruits)
print (f"打乱后的列表:{fruits} " )
print (f"\n=== 随机分布 ===" )
print (f"1.5-4.5 均匀分布:{random.uniform(1.5 , 4.5 ):.2 f} " )
print (f"正态分布(均值 0,标准差 1): {random.gauss(0 , 1 ):.2 f} " )
print (f"\n=== 随机字符串 ===" )
random_letters = "" .join(random.choices(string.ascii_lowercase, k=8 ))
print (f"8 位随机小写字母:{random_letters} " )
random_digits = "" .join(random.choices(string.digits, k=6 ))
print (f"6 位随机数字:{random_digits} " )
password_chars = string.ascii_letters + string.digits + "!@#$%^&*"
random_password = "" .join(random.choices(password_chars, k=10 ))
print (f"10 位随机密码:{random_password} " )
print (f"\n=== 随机种子 ===" )
random.seed(42 )
print (f"种子 42 的第一个随机数:{random.random()} " )
print (f"种子 42 的第二个随机数:{random.random()} " )
random.seed(42 )
print (f"重新设置种子 42 的第一个随机数:{random.random()} " )
datetime 模块 - 时间和日期管理 from datetime import datetime, date, time, timedelta
import time as time_module
print ("=== Datetime 模块功能演示 ===" )
print (f"\n=== 当前时间 ===" )
now = datetime.now()
today = date.today()
current_time = now.time()
print (f"当前完整时间:{now} " )
print (f"当前日期:{today} " )
print (f"当前时间:{current_time} " )
print (f"时间戳:{now.timestamp()} " )
print (f"\n=== 创建特定时间 ===" )
birthday = datetime(2000 , 5 , 15 , 14 , 30 , 0 )
print (f"生日:{birthday} " )
print (f"生日年份:{birthday.year} " )
print (f"生日月份:{birthday.month} " )
print (f"生日日期:{birthday.day} " )
print (f"生日小时:{birthday.hour} " )
print (f"生日分钟:{birthday.minute} " )
print (f"\n=== 时间格式化 ===" )
print (f"ISO 格式:{now.isoformat()} " )
print (f"自定义格式:{now.strftime('%Y 年%m 月%d日 %H 时%M分%S 秒' )} " )
print (f"星期几(0=周一): {now.weekday()} " )
print (f"星期几(英文): {now.strftime('%A' )} " )
print (f"月份(英文): {now.strftime('%B' )} " )
print (f"\n=== 时间计算 ===" )
print (f"现在:{now} " )
one_day = timedelta(days=1 )
one_hour = timedelta(hours=1 )
one_week = timedelta(weeks=1 )
print (f"明天:{now + one_day} " )
print (f"昨天:{now - one_day} " )
print (f"一小时后:{now + one_hour} " )
print (f"一周后:{now + one_week} " )
print (f"\n=== 时间差 ===" )
start_time = datetime(2024 , 1 , 1 , 8 , 0 , 0 )
end_time = datetime(2024 , 1 , 1 , 17 , 30 , 0 )
time_difference = end_time - start_time
print (f"开始时间:{start_time} " )
print (f"结束时间:{end_time} " )
print (f"时间差:{time_difference} " )
print (f"总秒数:{time_difference.total_seconds()} " )
print (f"天数:{time_difference.days} " )
print (f"秒数(除去天数): {time_difference.seconds} " )
print (f"\n=== 时间休眠 ===" )
print ("开始等待 2 秒..." )
time_module.sleep(2 )
print ("等待结束!" )
print (f"\n=== 程序运行时间 ===" )
start = time_module.time()
total = 0
for i in range (1000000 ):
total += i
end = time_module.time()
print (f"计算完成,用时:{end - start:.4 f} 秒" )
os 模块 - 操作系统接口 import os
import sys
print ("=== OS 模块功能演示 ===" )
print (f"\n=== 文件和目录 ===" )
print (f"当前工作目录:{os.getcwd()} " )
print (f"当前用户:{os.getlogin()} " )
print (f"当前进程 ID: {os.getpid()} " )
print (f"\n当前目录内容:" )
for item in os.listdir('.' ):
if os.path.isfile(item):
type_label = "文件"
elif os.path.isdir(item):
type_label = "目录"
else :
type_label = "其他"
if os.path.isfile(item):
size = os.path.getsize(item)
print (f" {item} ({type_label} , {size} 字节)" )
else :
print (f" {item} ({type_label} )" )
print (f"\n=== 路径操作 ===" )
file_path = "/home/user/documents/report.txt"
print (f"完整路径:{file_path} " )
print (f"目录名:{os.path.dirname(file_path)} " )
print (f"文件名:{os.path.basename(file_path)} " )
print (f"分割路径:{os.path.split(file_path)} " )
print (f"分割扩展名:{os.path.splitext(file_path)} " )
new_path = os.path.join("documents" , "reports" , "annual.pdf" )
print (f"构建的路径:{new_path} " )
print (f"\n=== 文件属性 ===" )
test_file = "example.txt"
with open (test_file, 'w' ) as f:
f.write("这是一个测试文件" )
print (f"文件存在:{os.path.exists(test_file)} " )
print (f"是文件:{os.path.isfile(test_file)} " )
print (f"是目录:{os.path.isdir(test_file)} " )
print (f"文件大小:{os.path.getsize(test_file)} 字节" )
print (f"最后修改时间:{os.path.getmtime(test_file)} " )
print (f"最后访问时间:{os.path.getatime(test_file)} " )
print (f"\n=== 环境变量 ===" )
print (f"PATH: {os.getenv('PATH' , '未设置' )} " )
print (f"HOME: {os.getenv('HOME' , '未设置' )} " )
print (f"USER: {os.getenv('USER' , '未设置' )} " )
print (f"PYTHONPATH: {os.getenv('PYTHONPATH' , '未设置' )} " )
print (f"\n=== 系统信息 ===" )
print (f"操作系统类型:{os.name} " )
print (f"路径分隔符:{repr (os.sep)} " )
print (f"换行符:{repr (os.linesep)} " )
print (f"\n=== 进程管理 ===" )
print (f"命令行参数:{sys.argv} " )
print (f"Python 版本:{sys.version} " )
print (f"\n=== 系统命令 ===" )
if os.name == 'nt' :
os.system('echo Hello from Windows' )
else :
os.system('echo "Hello from Unix-like system"' )
os.remove(test_file)
print (f"\n已删除测试文件:{test_file} " )
5. Python 面向对象编程 (OOP)
5.1 类与对象的基本概念
什么是类和对象?
类 :就像设计图纸 ,定义了对象的蓝图
对象 :就像根据图纸制造的具体产品
class Student :
"""学生类 - 就像学生这个概念的蓝图"""
def __init__ (self, name, age, score ):
self .name = name
self .age = age
self .score = score
def introduce (self ):
"""方法:自我介绍"""
return f"我叫{self.name} ,今年{self.age} 岁"
def study (self, hours ):
"""方法:学习"""
self .score += hours * 0.5
return f"学习了{hours} 小时,分数提升了{hours * 0.5 } "
student1 = Student("小明" , 18 , 85 )
student2 = Student("小红" , 17 , 92 )
print (student1.introduce())
print (student2.study(2 ))
print (f"{student2.name} 的分数:{student2.score} " )
5.2 封装:保护内部数据 封装就像把东西放进保险箱 - 内部细节被保护,只通过特定接口访问。
class BankAccount :
def __init__ (self, initial_balance=0 ):
self .__balance = initial_balance
def deposit (self, amount ):
"""存款 - 只能通过这个方法存钱"""
if amount > 0 :
self .__balance += amount
return f"存款成功,当前余额:{self.__balance} "
else :
return "存款金额必须大于 0"
def withdraw (self, amount ):
"""取款 - 只能通过这个方法取钱"""
if amount > self .__balance:
return "余额不足"
elif amount <= 0 :
return "取款金额必须大于 0"
else :
self .__balance -= amount
return f"取款成功,当前余额:{self.__balance} "
def get_balance (self ):
"""查看余额 - 只能通过这个方法看余额"""
return self .__balance
account = BankAccount(1000 )
print (account.deposit(500 ))
print (account.withdraw(200 ))
print (account.get_balance())
5.3 继承:家族传承 继承就像家族传承 - 子类继承父类的特征,还可以有自己的特色。
class Animal :
"""动物基类 - 所有动物的共同特征"""
def __init__ (self, name ):
self .name = name
def speak (self ):
return "动物发出声音"
def eat (self ):
return f"{self.name} 在吃东西"
class Dog (Animal ):
"""狗类 - 继承自动物,还有狗的特色"""
def speak (self ):
return "汪汪!"
def fetch (self ):
return f"{self.name} 在接飞盘"
class Cat (Animal ):
"""猫类 - 继承自动物,还有猫的特色"""
def speak (self ):
return "喵喵!"
def climb (self ):
return f"{self.name} 在爬树"
dog = Dog("旺财" )
cat = Cat("咪咪" )
print (dog.speak())
print (cat.speak())
print (dog.eat())
print (dog.fetch())
5.4 多态:同一指令,不同反应 多态就像同一指令,不同反应 - 不同对象对同一方法有不同的实现。
class Shape :
"""形状基类"""
def area (self ):
pass
class Circle (Shape ):
def __init__ (self, radius ):
self .radius = radius
def area (self ):
return 3.14 * self .radius ** 2
class Rectangle (Shape ):
def __init__ (self, width, height ):
self .width = width
self .height = height
def area (self ):
return self .width * self .height
class Triangle (Shape ):
def __init__ (self, base, height ):
self .base = base
self .height = height
def area (self ):
return 0.5 * self .base * self .height
shapes = [Circle(5 ), Rectangle(4 , 6 ), Triangle(3 , 4 )]
for shape in shapes:
print (f"形状面积:{shape.area():.2 f} " )
学习建议
如何学好 Python?
理解概念比死记硬背更重要
把编程概念与现实生活联系起来
多用比喻理解抽象概念
多动手实践
每个例子都要自己敲一遍
尝试修改例子看看会发生什么
从简单到复杂
先掌握基础语法
再学习数据结构和函数
最后学习面向对象和高级特性
不要怕犯错
错误信息是学习的最好机会
通过调试理解程序运行原理
下一步学习路径
巩固基础 :反复练习变量、条件、循环
项目实践 :尝试写一些小程序,如计算器、猜数字游戏
学习高级主题 :文件操作、异常处理、网络编程
专业方向 :Web 开发、数据分析、人工智能等
记住,编程就像学骑自行车 - 开始可能会摔倒,但一旦掌握了,就会变得自然而然!
相关免费在线工具 加密/解密文本 使用加密算法(如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