
👉 项目官网:https://www.python-office.com/ 👈

大家好,这里是程序员晚枫,正在all in AI编程实战。
今天我们学习 Python 函数和模块化编程,让你的代码更简洁、更易维护!
1、什么是函数?
函数就是一段可以重复使用的代码块:
1 2 3 4 5 6 7
| def say_hello(): print('Hello!') print('你好!')
say_hello()
|
2、函数的参数
1 2 3 4 5 6 7 8 9 10 11 12 13
| def greet(name): print(f'你好,{name}!')
greet('张三') greet('李四')
def greet(name, age=18): print(f'你好,{name}!你{age}岁了。')
greet('张三') greet('李四', 20)
|
3、返回值
1 2 3 4 5 6
| def add(a, b): return a + b
result = add(3, 5) print(result)
|
4、模块化:把代码分成多个文件
把常用函数放到单独的文件里:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
def format_money(amount): """格式化金额""" return f'¥{amount:,.2f}'
def format_phone(phone): """格式化手机号""" return f'{phone[:3]}-{phone[3:7]}-{phone[7:]}'
def validate_email(email): """验证邮箱""" return '@' in email
|
然后在其他文件里使用:
1 2 3 4 5 6 7 8 9
|
from utils import format_money, format_phone
money = format_money(1234567.89) print(money)
phone = format_phone('13812345678') print(phone)
|
5、实战案例:模块化处理Excel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
import office
def read_sales(file_path): """读取销售数据""" return office.excel.read(path=file_path)
def calculate_total(df): """计算销售总额""" return df['销售额'].sum()
def generate_summary(df): """生成汇总数据""" return { 'total': calculate_total(df), 'count': len(df), 'avg': df['销售额'].mean() }
|
1 2 3 4 5 6 7 8 9
|
from excel_utils import read_sales, generate_summary
df = read_sales('销售数据.xlsx') summary = generate_summary(df)
print(f'总销售额:¥{summary["total"]:,.2f}') print(f'订单数:{summary["count"]}')
|
6、实战案例:模块化邮件发送
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
import office from datetime import date
def send_daily_report(file_path, recipients): """发送日报""" today = date.today().strftime('%Y-%m-%d') for recipient in recipients: office.email.send( email=recipient, title=f'【日报】{today}', content=f'您好,{today}的报告请查收。', attachment=file_path ) return len(recipients)
def send_reminder(message, recipients): """发送提醒""" for recipient in recipients: office.email.send( email=recipient, title='提醒', content=message )
|
1 2 3 4 5 6 7 8
|
from email_utils import send_daily_report
send_daily_report( file_path='日报.xlsx', recipients=['领导@example.com', '主管@example.com'] )
|
7、总结
模块化编程的好处:
- ✅ 代码复用:写一次,用多次
- ✅ 易于维护:修改一处,不影响其他
- ✅ 结构清晰:每个文件功能分明
- ✅ 团队协作:各人负责不同模块
8、下讲预告
学会了模块化,下一讲我们学 Python进阶:错误处理和调试。
敬请期待!
有问题欢迎加微信 python-office 进群交流~
程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。
🎓 AI 编程实战课程
想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!