Python项目代码太多if-else? 这样优化才优雅!

前言

代码中不可避免地会出现复杂的if-else条件逻辑,而简化这些条件表达式是一种提高代码可读性极为实用的技巧。

在 Python 中,有多种方法可以避免复杂的 if-else 条件逻辑,使代码更加清晰和易于维护。

筑基期

提前 return,去掉多余的 else

在 Python 中,使用"提前返回"(early return)可以避免深层嵌套的if-else语句,并且使代码更加清晰。

场景:电商平台为首次购买的用户在结账时提供优惠券。如果用户不是首次购买,或者购物车中的商品总额低于某个阈值,则不提供优惠券。

未使用提前返回的原始代码

def apply_coupon(user, cart):
    if user.is_first_purchase:
        if cart.total_amount >= 100:
            cart.apply_discount(10)  # 应用10%的折扣
            print("A coupon has been applied to your purchase.")
        else:
            print("Your purchase does not meet the minimum amount for a coupon.")
    else:
        print("Coupons are only available for first-time purchases.")
    return cart

使用提前返回优化后的代码

def apply_coupon(user, cart):
    # 检查是否为首次购买
    if not user.is_first_purchase:
        print("Coupons are only available for first-time purchases.")
        return cart

    # 检查购物车总额是否满足条件
    if cart.total_amount < 100:
        print("Your purchase does not meet the minimum amount for a coupon.")
        return cart

    # 应用优惠券
    cart.apply_discount(10)  # 应用10%的折扣
    print("A coupon has been applied to your purchase.")
    return cart

首先,定义用户和购物车类,以及必要的属性和方法:

class User:
    def __init__(self, is_first_purchase):
        self.is_first_purchase = is_first_purchase

class Cart:
    def __init__(self, total_amount):
        self.total_amount = total_amount
        self.discount = 0

    def apply_discount(self, percentage):
        self.discount = self.total_amount * (percentage / 100)
        self.total_amount -= self.discount

    def __str__(self):
        return f"Cart(total_amount={
     self.total_amount}, discount={
     self.discount})"

然后,我们创建两个用户和两个购物车对象。

  • 第一个用户是首次购买,购物车总额为150,满足应用优惠券的条件,因此会看到优惠券被应用,并且购物车总额减少。
  • 第二个用户不是首次购买,购物车总额为50,不满足应用优惠券的条件,因此会看到相应的提示信息,购物车总额不变。
# 创建用户对象,假设是首次购买
user = User(is_first_purchase=True)

# 创建购物车对象,假设购物车总额为150
cart = Cart(total_amount=150)

# 打印原始购物车状态
print("原始购物车状态:", cart)

# 调用apply_coupon函数
cart = apply_coupon(user, cart)

# 打印应用优惠券后的购物车状态
print("应用优惠券后的购物车状态:", cart)

# 再次创建一个购物车对象,假设购物车总额为50,且用户不是首次购买
another_user = User(is_first_purchase=False)
another_cart = Cart(total_amount=50)

# 打印原始购物车状态
print("\n原始购物车状态:", another_cart)

# 调用apply_coupon函数
another_cart = apply_coupon(another_user, another_cart)

# 打印应用优惠券后的购物车状态(实际上不会应用优惠券)
print("应用优惠券后的购物车状态(实际上不会应用优惠券):", another_cart)

在这个优化后的版本中,我们使用了提前返回来简化逻辑流程:

  1. 首先检查用户是否为首次购买,如果不是,则立即返回,不再执行后续代码。
  2. 然后检查购物车总额是否满足优惠券的最低限额,如果不满足,同样立即返回。
  3. 只有当这两个条件都满足时,才应用优惠券并打印相应的消息。

提前返回的好处

  • 逻辑清晰:每个条件都被单独检查,并且不满足时立即返回,逻辑流程非常清晰。
  • 减少嵌套:避免了深层嵌套的if-else结构,使得代码更加扁平化。
  • 易于维护:当需要修改条件或者添加新的条件时,可以很容易地在函数开头添加新的检查。
  • 避免冗余:去掉了不必要的else语句,因为每个if语句都有明确的返回点。

通过这种方式,提前返回使得代码更加简洁、直观,并且易于理解和维护。

使用合适的逻辑运算符

Python开发中,逻辑运算符andorinbool()not等可以帮助我们简化条件判断,从而减少if语句的使用。以下是使用逻辑运算符优化if语句的一个电商例子。

场景:电商平台想要为特定条件下的用户提供优惠券。条件包括:

  • 用户必须是新用户(is_new 属性为 True)。
  • 用户的购物车中必须包含至少一种电子产品(category 属性为 "electronics")。
  • 用户的购物车总价必须超过一定金额(例如200元)。

未使用逻辑运算符的原始代码

from collections import namedtuple


def apply_coupon(_cart_items, _user):
    if _user.is_new:
        if any(item['category'] == 'electronics' for item in _cart_items):
            if sum(item['price'] * item['quantity'] for item in _cart_items) > 200:
                # 应用优惠券逻辑
                print("Coupon applied!")
            else:
                print("Cart total is less than 200.")
        else:
            print("No electronics in cart.")
    else:
        print("User is not new.")


# 示例用户和购物车
User = namedtuple('User', ["is_new"])
user = User(is_new=True)
cart_items = [
    {
   'name': 'Laptop', 'category': 'electronics', 'price': 150, 'quantity': 1},
    {
   'name': 'Book', 'category': 'books', 'price': 50, 'quantity': 2},
]

apply_coupon(cart_items, user)  # Coupon applied!

使用逻辑运算符优化后的代码

from collections import namedtuple


def apply_coupon(cart_items, user):
    # 使用逻辑运算符组合条件
    new_user = user.is_new
    has_electronics = any(item['category'] == 'electronics' for item in cart_items)
    cart_total = sum(item['price'] * item['quantity'] for item in cart_items) > 200

    # 如果所有条件都满足,则应用优惠券
    if new_user and has_electronics and cart_total:
        print("Coupon applied!")
    else:
        print("Coupon not applied.")


# 示例用户和购物车
User = namedtuple('User', ["is_new"])
user = User(is_new=True)
cart_items = [
    {
   'name': 'Laptop', 'category': 'electronics', 'price': 150, 'quantity': 1},
    {
   'name': 'Book', 'category': 'books', 'price': 50, 'quantity': 2},
]

apply_coupon(cart_items, user)  # Coupon applied!

在这个优化后的版本中,我们首先使用逻辑运算符来单独评估每个条件:

  • new_user 检查用户是否为新用户。
  • has_electronics 检查购物车中是否有电子产品。
  • cart_total 检查购物车总价是否超过 200 元。

然后,我们使用and运算符来确保所有条件都满足,只有当这个组合条件为真时,才应用优惠券。

使用逻辑运算符的好处包括:

  1. 代码简化:减少了嵌套的if语句,使代码更加简洁。
  2. 逻辑清晰:每个条件的评估清晰明了,易于理解和维护。
  3. 易于调整:如果需要修改条件或添加新条件,只需调整逻辑表达式即可。

通过这种方式,逻辑运算符帮助我们编写出更加Pythonic和易于维护的代码。

提炼条件判断逻辑

当条件判断变得过于复杂时,它不仅难以理解,还可能导致代码维护困难。将复杂的条件判断逻辑提炼成独立的函数是一种很好的实践,这样可以使代码更加清晰、可读性更高,并且易于维护。

假设我们有一个函数,根据用户的购物车中的商品种类和数量来决定是否提供折扣。原始的代码可能包含多个嵌套的if-else语句,如下所示:

def calculate_discount(_cart_items):
    discount = 0
    if 'electronics' in _cart_items:
        if len(_cart_items['electronics']) >= 3:
            discount += 10
        if 'laptop' in _cart_items['electronics']:
            discount += 5
    elif 'clothing' in _cart_items:
        if len(_cart_items['clothing']) >= 5:
            discount += 15
    # ... 更多条件
    return discount

这个函数的可读性很差,很难一眼看出它在做什么。我们可以将复杂的条件判断逻辑提炼成独立的函数,如下所示:

# 定义检查商品的函数
def has_bulk_electronic_items(_cart_items):
    return len(_cart_items.get('electronics', [])) >= 3


def has_laptop_in_electronics(_cart_items):
    return 'laptop' in _cart_items.get('electronics', [])


def has_many_clothing_items(_cart_items):
    return len(_cart_items.get('clothing', [])) >= 5


# 定义计算折扣的函数
def calculate_discount(_cart_items):
    discount = 0
    if has_bulk_electronic_items(_cart_items):
        discount += 10  # 电子产品数量超过3个,折扣10%
    if has_laptop_in_electronics(_cart_items):
        discount += 5  # 电子产品中有笔记本电脑,额外折扣5%
    if has_many_clothing_items(_cart_items):
        discount += 15  # 服装数量超过5个,折扣15%
    
  • 25
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海哥python

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值