变量:点单系统
# 奶茶店点单系统
customer = "张三" # 字符串类型变量
cup_size = "大杯" # 字符串类型变量
price = 16 # 整型变量
sugar_level = 0.5 # 浮点型变量(半糖)
topping = ["珍珠", "布丁"] # 列表类型变量
has_straw = True # 布尔类型变量
# 打印订单详情(使用f-string格式化)
print(f"""
=== {customer}的奶茶订单 ===
规格:{cup_size}
甜度:{sugar_level*100}%糖
加料:{'、'.join(topping)}
吸管:{'提供' if has_straw else '不提供'}
金额:{price}元
""")
# 修改订单信息(变量重新赋值)
cup_size = "超大杯"
price += 3
topping.append("椰果")
print(f"修改后:{cup_size},加料{topping},总价{price}元")
类型:记账本
# 智能记账本系统
transactions = [] # 用列表记录所有交易
# 记录不同类型消费
transactions.append(("餐饮", 25.5, "牛肉面")) # 元组存储
transactions.append(("交通", 6.0, "地铁"))
transactions.append(("娱乐", 88.8, "电影票"))
# 自动统计消费
total = 0
category_expense = {} # 字典统计分类开支
for record in transactions:
category = record[0]
amount = float(record[1]) # 显式类型转换
total += amount
category_expense[category] = category_expense.get(category, 0) + amount
# 格式化输出报表
print(" 本月消费分析")
print(f"总支出: {total:.2f}元") # 保留两位小数
print("分类明细:")
for category, money in category_expense.items():
print(f"- {category}: {money}元")
# 类型检查增强健壮性
if isinstance(total, float):
print("\n(类型校验通过)")
格式化:情书
# 情书生成器
import datetime
def generate_love_letter(name, adjectives, days):
# 使用三重引号的多行字符串
template = f"""
亲爱的{name}:
自从遇见你,我的世界变得{adjectives[0]}又{adjectives[1]}。
你的眼睛像{adjectives[2]}的星辰,照亮了我{days}天的等待。
每一天都想与你:
1. 一起看{adjectives[3]}的日出
2. 品尝{adjectives[4]}的咖啡
3. 走过{adjectives[5]}的街道
期待回信的:Python助手
日期:{datetime.date.today()}
"""
return template
# 用户输入参数
user_name = input("请输入对方名字:")
custom_adjs = ["甜蜜", "温暖", "闪耀", "浪漫", "香醇", "落叶缤纷"]
dating_days = 365
# 生成并打印情书
print(generate_love_letter(user_name, custom_adjs, dating_days))
分支结构:智能体重秤
# 智能健康评估系统
def body_analysis():
# 输入处理与类型转换
height = float(input("请输入身高(m):"))
weight = float(input("请输入体重(kg):"))
bmi = weight / (height ** 2)
# 多条件分支结构
print(f"\nBMI:{bmi:.1f}")
if bmi < 18.5:
tag = "过轻"
advice = "建议增加营养摄入"
elif 18.5 <= bmi < 24:
tag = "正常"
advice = "保持良好习惯"
elif 24 <= bmi < 28:
tag = "过重"
advice = "建议控制饮食"
else:
tag = "肥胖"
advice = "请咨询专业医生"
# 格式化输出结果
print(f"状态:{tag}")
print(f"健康建议:{advice}")
print("="*30)
# 附加功能:单位转换
pounds = weight * 2.2046
print(f"国际单位:{pounds:.1f}磅")
# 执行函数
body_analysis()
# 测试案例:尝试输入1.75和70kg
循环:视频解析器
# 短视频热度分析系统
videos = [
{"title": "Python技巧", "likes": 15000, "comments": 420},
{"title": "健身教学", "likes": 8500, "comments": 150},
{"title": "美食测评", "likes": 23000, "comments": 980}
]
# 筛选爆款视频(点赞>1w且评论>300)
print(" 今日爆款视频:")
hot_count = 0
for index, video in enumerate(videos, 1):
# 复合条件判断
if video["likes"] > 10000 and video["comments"] > 300:
hot_count += 1
# 字符串格式化输出
print(f"{index}. [{video['title']}]")
print(f" {video['likes']} | {video['comments']}")
print(f" 热度值:{(video['likes'] + video['comments']*10):,}")
print("-" * 30)
# 循环统计结果
print(f"共发现{hot_count}个爆款视频")
嵌套:自动生成诗词藏头
# 藏头诗生成器
def create_acrostic(head_words):
poem_lines = []
# 预设诗句库
word_bank = {
"春": ["春眠不觉晓", "春风送暖入屠苏", "春江潮水连海平"],
"秋": ["秋风起兮白云飞", "秋水共长天一色", "秋收万颗子"],
"月": ["月落乌啼霜满天", "月照花林皆似霰", "月明千里照平沙"],
"花": ["花间一壶酒", "花开堪折直须折", "花自飘零水自流"]
}
# 嵌套循环结构
for char in head_words:
found = False
# 遍历字典查找匹配诗句
for keyword, verses in word_bank.items():
if char in keyword:
poem_lines.append(verses[0]) # 取第一个匹配诗句
found = True
break
if not found:
poem_lines.append(f"{char}开头的诗句待补充") # 容错处理
# 美化输出格式
border = "" * 20
print(f"\n{border}\n《{'·'.join(head_words)}》\n")
for line in poem_lines:
print(f" {line}")
print(f"\n{border}")
# 使用示例
create_acrostic("春夏秋冬") # 尝试修改参数
函数:打造个人指令集
# 智能文件处理工具包
def file_operator(action: str, path: str, content: str = None) -> bool:
"""
文件操作瑞士军刀
:param action: read/write/append/delete
:param path: 文件路径
:param content: 写入内容(可选)
:return: 操作是否成功
"""
try:
if action == "read":
with open(path, 'r', encoding='utf-8') as f:
return f.read()
elif action == "write":
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
elif action == "append":
with open(path, 'a', encoding='utf-8') as f:
f.write(content)
elif action == "delete":
import os
os.remove(path)
else:
raise ValueError("无效操作类型")
return True
except Exception as e:
print(f"操作失败:{str(e)}")
return False
# 使用示例
file_operator('write', 'todo.txt', '1.完成周报\n') # 写入文件
print(file_operator('read', 'todo.txt')) # 读取文件
模块:操作文件
import os
import datetime
def generate_weekly_report(projects: list, output_path: str):
"""自动生成标准周报"""
time_str = datetime.datetime.now().strftime("%y/%m/%d")
# 使用闭包记录报告生成次数
def counter():
count = 0
def inner():
nonlocal count
count += 1
return count
return inner
count_func = counter()
# 生成报告内容
report = f"【周报】{time_str}\n\n"
report += "=" * 30 + "\n"
for project in projects:
report += f"{count_func()}. {project['name']} - 进度 {project['progress']}%\n"
report += f" 本周成果:{project['achievements']}\n\n"
# 文件操作
if not os.path.exists('reports'):
os.makedirs('reports')
with open(f'reports/{output_path}', 'w', encoding='utf-8') as f:
f.write(report)
print(f"周报已生成至:reports/{output_path}")
def batch_rename(dir_path: str, prefix: str):
"""
批量重命名工具,将指定目录下的所有文件按规则重命名。
:param dir_path: 要操作的目录路径
:param prefix: 文件名前缀
:raises FileNotFoundError: 如果指定的目录不存在
:raises NotADirectoryError: 如果传入的路径不是一个目录
"""
# 检查目录是否存在
if not os.path.exists(dir_path):
raise FileNotFoundError(f"指定的目录 {dir_path} 不存在")
# 检查是否为目录
if not os.path.isdir(dir_path):
raise NotADirectoryError(f"{dir_path} 不是一个目录")
for idx, filename in enumerate(os.listdir(dir_path)):
file_path = os.path.join(dir_path, filename)
# 跳过目录,只处理文件
if os.path.isfile(file_path):
ext = os.path.splitext(filename)[1]
new_name = f"{prefix}_{idx + 1:03d}{ext}" # 文件重命名
new_path = os.path.join(dir_path, new_name)
try:
os.rename(file_path, new_path)
except Exception as e:
print(f"重命名文件 {filename} 时出错: {e}")
def get_file_info(filepath: str):
"""
获取文件元信息,包括文件大小、创建时间和修改时间。
:param filepath: 要获取信息的文件路径
:return: 包含文件元信息的字典
:raises FileNotFoundError: 如果指定的文件不存在
"""
# 检查文件是否存在
if not os.path.exists(filepath):
raise FileNotFoundError(f"指定的文件 {filepath} 不存在")
# 检查是否为文件
if not os.path.isfile(filepath):
raise ValueError(f"{filepath} 不是一个文件")
stat = os.stat(filepath)
return {
"size": f"{stat.st_size / 1024:.1f}KB",
"created": datetime.fromtimestamp(stat.st_ctime),
"modified": datetime.fromtimestamp(stat.st_mtime)
}
# 调用示例(需先创建test_files目录)
if __name__ == "__main__":
current_path = os.path.dirname(os.path.abspath(__file__))
# 使用示例
projects = [
{'name': 'AI模型优化', 'progress': 75, 'achievements': '准确率提升3%'},
{'name': '自动化平台', 'progress': 90, 'achievements': '完成接口联调'}
]
generate_weekly_report(projects, 'week_16_report.txt')
try:
batch_rename(current_path+"\\reports\\", "week_16_report") #文件名会被重命名
# print(get_file_info(current_path+"\\reports\\week_16_report_001.txt")) #查看文件注意文件名
except (FileNotFoundError, NotADirectoryError, ValueError) as e:
print(f"操作出错: {e}")
实战:生成周报工具
# 周报生成系统
from datetime import datetime, timedelta
import random
# 定义常量,提高代码可维护性
TASK_LIST = [
"需求开发", "代码评审", "技术调研",
"BUG修复", "文档编写", "会议讨论"
]
BLOCKER_LIST = ["需求变更", "环境问题", "第三方延迟"]
NEXT_WEEK_PLAN = [
"推进剩余开发任务",
"组织代码评审会议",
"输出技术文档"
]
class WeeklyReport:
"""周报自动化生成器"""
def __init__(self, name: str):
self.user = name
def _gen_task_list(self) -> list:
"""随机生成任务列表"""
return random.sample(TASK_LIST, k=3)
def _calc_progress(self) -> dict:
"""生成进度数据"""
completed = random.randint(70, 95)
blockers_count = random.randint(0, 2)
blockers = BLOCKER_LIST[:blockers_count]
return {
"completed": completed,
"blockers": blockers
}
def _format_task_list(self, tasks: list) -> str:
"""格式化任务列表"""
return ''.join(f'· {task}\n' for task in tasks)
def _format_blockers(self, blockers: list) -> str:
"""格式化存在问题"""
return '无' if not blockers else ', '.join(blockers)
def _get_week_period(self) -> tuple:
"""获取周报周期"""
start_date = datetime.now() - timedelta(days=7)
end_date = datetime.now()
return start_date, end_date
def generate(self) -> str:
"""生成周报文档"""
start_date, end_date = self._get_week_period()
progress = self._calc_progress()
task_list = self._gen_task_list()
report = f"""
=== {self.user}的周报 ===
周期:{start_date:%Y-%m-%d} 至 {end_date:%Y-%m-%d}
本周工作:
{self._format_task_list(task_list)}
项目进度:{progress['completed']}%
存在问题:{self._format_blockers(progress['blockers'])}
下周计划:
{self._format_task_list(NEXT_WEEK_PLAN)}
"""
return report.strip()
# 使用示例
engineer = WeeklyReport("张三")
print(engineer.generate())