joeの小窝

Loading...

函数案例

案例1(递归函数)

递归函数,自己调用自己

计算5!

def fun(num):
    if num == 1:
        return 1
    return  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(学生信息管理函数)

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

# **info里面接收多个数据的话,就是一个字典
# info = {"sex":"男","score":90} 这样的数据
# 使用update添加一个新的字典,添加到原字典中去
def add_student(name,age=18,**info):
    """

    :param name: 学生姓名
    :param age: 学生年龄
    :param info: 学生其他信息,成绩,性别等等
    :return: 返回学生字典
    """
    # 添加信息,字典的方式
    student = {"name":name,"age":age}
    student.update(info)
    # 返回是一个学生字典
    return student

# *student 里面存储多个数据的话,就是一个元组 
# student = ({"name":"zhangsan","age":18},{}) 这样的数据,元组里面存储的是多个字典
def show_all(*student):
    for s in student:
        print(s)

s1 = add_student("张三",18,sex="男",score=90)
s2 = add_student("李四",score=88)

show_all(s1,s2)

案例3(购物车结算)

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

添加商品函数:add_item(cart,name,price,quantity)
cart是商品列表,name商品名字,price单价,quantity商品数量

需要考虑的就是商品是否存在,存在就更新商品数量
不存在就添加商品
----------------------

计算总价函数:calculate_total(cart)
cart商品列表
return 返回商品总价

-----------------

计算折扣金额函数:get_discount(total_price,discount_rate=1.0)
total_price商品总价
discount_rate为折扣率,默认不打折扣
return 返回折扣后的价格

--------------

计算运费函数: calculate_shipping(discount_price,shipping_fee=10,free_shipping_threshold=99)

discount_price 折扣后的价格

shipping_fee 基础运费

free_shipping_threshold 免运费门槛

-------------

最终订单函数 checkout(cart,discount_rate=1.0):

cart购物车列表
折扣率

这个函数里面调用计算商品总价,折扣,运费这个三个函数

算出最终的价格

打印清单
每个商品姓名,数量,价格

商品总价

折扣后的价格

运费

最终应付



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"] += quantity
            print(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 = 0
    for item in cart:
        total += item["price"] * item["quantity"]
    return total


def get_discount(total_price, discount_rate=1.0):
    """
    计算折扣金额
    :param total_price: 商品总价
    :param discount_rate: 折扣率(如0.9=9折,默认不打折)
    :return: 折扣后价格
    """
    discounted_price = total_price * discount_rate
    return discounted_price


def 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 0
    return shipping_fee


def 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 的流程像"清单"一样清晰:总价 → 折扣 → 运费 → 最终
posted @ 2026-05-25 20:44  乔的港口  阅读(4)  评论(0)    收藏  举报