当前位置: 首页 > news >正文

函数案例

案例1(递归函数)

递归函数,自己调用自己

计算5!

def fun(num):if num == 1:return 1return  num*fun(num-1)result = fun(5)
print(result)# 过程
"""
fun(5) = 5*fun(4)  5*4*3*2*1
fun(4) = 4*fun(3) 4*3*2*1
fun(3) = 3*fun(2) 3*2*1
fun(2) = 2*fun(1) 2*1
fun(1) = 1"""

案例2(学生信息管理函数)

功能:录入学生信息,批量添加、打印信息,用到位置参数、关键字参数、不定长参数

案例3(购物车结算)

功能:添加商品,计算总价,折扣计算,运费计算,最终结算功能

def add_item(cart, name, price, quantity=1):"""向购物车添加商品:param cart: 购物车列表(存储所有商品):param name: 商品名称:param price: 商品单价:param quantity: 商品数量,默认1"""# 检查商品是否已存在,存在则累加数量for item in cart:if item["name"] == name:item["quantity"] += quantityprint(f"已更新【{name}】数量为:{item['quantity']}")return# 商品不存在,新增商品cart.append({"name": name, "price": price, "quantity": quantity})print(f"已添加商品:{name},单价:{price},数量:{quantity}")def calculate_total(cart):"""计算购物车商品总价(不含运费、折扣):param cart: 购物车列表:return: 商品总价"""total = 0for item in cart:total += item["price"] * item["quantity"]return totaldef get_discount(total_price, discount_rate=1.0):"""计算折扣金额:param total_price: 商品总价:param discount_rate: 折扣率(如0.9=9折,默认不打折):return: 折扣后价格"""discounted_price = total_price * discount_ratereturn discounted_pricedef calculate_shipping(discounted_price, free_shipping_threshold=99, shipping_fee=10):"""计算运费:满99元免运费,不满则收10元运费:param discounted_price: 折扣后价格:param free_shipping_threshold: 免运费门槛:param shipping_fee: 基础运费:return: 运费金额"""if discounted_price >= free_shipping_threshold:return 0return shipping_feedef checkout(cart, discount_rate=1.0):"""购物车最终结算函数(核心):param cart: 购物车列表:param discount_rate: 折扣率:return: 最终应付金额"""# 1. 计算商品总价total_price = calculate_total(cart)if total_price == 0:print("购物车为空,无法结算!")return 0# 2. 计算折扣后价格discounted_price = get_discount(total_price, discount_rate)# 3. 计算运费shipping = calculate_shipping(discounted_price)# 4. 最终应付金额final_price = discounted_price + shipping# 打印结算详情print("\n" + "="*30)print("        购物车结算单")print("="*30)for item in cart:subtotal = item["price"] * item["quantity"]print(f"{item['name']} × {item['quantity']} 件:{subtotal:.2f} 元")print(f"商品总价:{total_price:.2f} 元")print(f"折扣后价格:{discounted_price:.2f} 元")print(f"运费:{shipping:.2f} 元")print("="*30)print(f"最终应付:{final_price:.2f} 元")print("="*30 + "\n")return final_price# ------------------- 测试案例 -------------------
if __name__ == "__main__":# 初始化空购物车shopping_cart = []# 添加商品add_item(shopping_cart, "笔记本电脑", 5999, 1)add_item(shopping_cart, "无线鼠标", 99, 2)add_item(shopping_cart, "无线鼠标", 99, 1)  # 重复添加,累加数量add_item(shopping_cart, "键盘", 199, 1)# 结算(使用9折优惠)checkout(shopping_cart, discount_rate=0.9)
# 分析函数checkout(购物车, 折扣率)          ← 最外层,总控函数│├── calculate_total(购物车)    ← 调用:算商品总价│├── get_discount(总价, 折扣率)  ← 调用:算折扣后价│└── calculate_shipping(折后价)  ← 调用:算运费(内部自己判断满99免运费)
优势 说明
职责单一 每个函数只做一件事:添加商品、算总价、算折扣、算运费、最终结算
可复用 calculate_total 可以单独调用,不限于 checkout 里用
易维护 改运费规则只需改 calculate_shipping,不影响其他函数
可读性强 checkout 的流程像"清单"一样清晰:总价 → 折扣 → 运费 → 最终
http://www.jsqmd.com/news/885813/

相关文章:

  • PurrNet实战:FPS联机同步与反作弊设计精要
  • LT1931负电源CUK电路
  • Windows Cleaner:终极免费系统清理工具,彻底解决C盘空间不足问题
  • 什么是数据库索引
  • Niagara特效避坑指南:从‘喷泉穿模’到完美碰撞,GPU模拟设置全流程
  • 避坑指南:UE程序化网格体切割时‘部分无法切割’问题排查与修复
  • 2026年国产便携式溶解氧仪十大品牌权威排行榜:技术实力与市场口碑深度解析 - 水质仪表品牌排行榜
  • Sora 2导出MOV时音频不同步?用这5行Python代码自动校准PTS/DTS并重写moov头(实测误差<2ms)
  • 04 - 运算符与表达式
  • 2026年C++与C语言结构差异解析:C++非C语言超集,迁移规则需明确
  • Icarus Verilog:3步解决数字电路仿真的开源利器
  • 如何构建你自己的自动驾驶操作系统:openpilot深度实践指南
  • 基于ConvNeXt的ECG呼吸率预测:从深度学习模型到临床早期预警
  • UE5跨关卡存档系统:SaveGame与GameInstance协同实战
  • Android Java层动态分析实战:Frida进阶Hook与反加固对抗
  • 接口测试需要验证数据库么?
  • 当大模型算法岗面试走进餐饮界,AI 能否让餐饮生意告别“经验主义”?
  • 2026年工业流体与自动化元件口碑推荐榜:SIWELL 四维增压泵、RM 增广智能、AMILA 亚米拉吸盘厂家选购指南 - 海棠依旧大
  • 网盘文件下载速度提升方案:LinkSwift直链获取工具全解析
  • PUBG罗技鼠标宏:3步打造终极压枪神器
  • macOS鼠标平滑滚动终极指南:让外接鼠标获得触控板般丝滑体验
  • SCADA系统研发:从数据采集到智能运维的完整解析
  • 如何在Windows上配置高性能视频渲染器:专业级播放体验完整指南
  • LinkSwift 网盘加速引擎架构解析:多协议直连实现方案
  • UE5新手避坑:3D UI控件(WidgetComponent)为啥点不动?手把手教你搞定鼠标交互
  • 淘金币自动化脚本:3步解放双手,每天节省25分钟!
  • 别再只用Sprite了!UE Niagara网格体渲染器实战:用自定义模型打造高级粒子特效
  • 四级证件照怎么制作?2026英语四六级报名照片尺寸要求+教程 - 科技大爆炸
  • UE5跨关卡数据持久化:SaveGame与GameInstance实战指南
  • 大模型应用开发:方法与案例