当前位置: 首页 > 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.gsyq.cn/news/1383610.html

相关文章:

  • 别再只会用Button了!用Unity EventSystem实现拖拽、滚动和键盘导航的5个实战案例
  • Sora 2导出MOV时音频不同步?用这5行Python代码自动校准PTS/DTS并重写moov头(实测误差<2ms)
  • Icarus Verilog:3步解决数字电路仿真的开源利器
  • 基于ConvNeXt的ECG呼吸率预测:从深度学习模型到临床早期预警
  • 告别建模小白:用ContextCapture 10.20.1把无人机照片变成Unity可用的3mx/OSGB模型(附避坑指南)
  • 【C语言】C 语言为什么叫 C 语言呢?
  • php有什么版本,php语言有几个版本
  • Claude模型能力边界全扫描:3大优势、2个致命弱点、5个未公开风险点(企业级部署必读)
  • 接口测试需要验证数据库么?
  • macOS鼠标平滑滚动终极指南:让外接鼠标获得触控板般丝滑体验
  • Unity URP管线下的PICO4 VR开发:从零配置可移动交互的虚拟角色(2021.3.27f1实测)
  • 昇腾NPU上部署YOLO系列——NPU端NMS与性能优化(完整版)
  • Avidemux视频编辑器的完整指南:如何用轻量级工具实现专业级剪辑效果
  • 别再只用Random.Range了!Unity随机数生成器(Random类)的5个实战技巧与常见误区
  • 别再只用Random.Range了!Unity随机数生成器(Random类)的5个实战技巧与避坑指南
  • 端到端延迟优化:从 LLM 到 Harness 层
  • 四级证件照怎么制作?2026英语四六级报名照片尺寸要求+教程 - 科技大爆炸
  • UE5对象池进阶:如何设计支持栈/队列模式、事件监听的灵活系统?
  • UE5蓝图实战:用程序化网格体组件实现物体动态切割(含物理分离与射线触发)
  • UE5蓝图实战:用程序化网格体组件实现鼠标点击切割任意模型(含物理分离效果)
  • 告别枯燥理论!用Unity脚本生命周期与预制体玩转一个“会变身的敌人”
  • Niagara特效避坑指南:从‘喷泉穿模’到完美碰撞,GPU模拟设置全流程
  • UE5 Niagara特效实战:用Simple Sprite Burst模板10分钟搞定写实烟雾效果
  • 【限时解密】Midjourney内部文档泄露片段:noise_floor阈值、dithering开关与--style raw的底层耦合逻辑(仅剩最后87份存档)
  • 从《原神》到你的项目:看VaRest插件如何成为虚幻引擎与后端服务的‘万能胶’
  • 别再只用Sprite了!UE Niagara网格体渲染器实战:用自定义模型打造高级粒子特效
  • SCADA系统研发:从数据采集到智能运维的完整解析
  • 在持续集成流程中集成TaoToken API进行自动化代码审查的实践
  • k6 Scenario深度解析:构建真实用户行为压测模型
  • 上蔡假发定制亲测:这家口碑超稳 - 资讯快报