Python 中条件语句的最佳实践

Python 中条件语句的最佳实践

本文解释了 Python 中条件语句的最佳实践。

YouTube Video

Python 中条件语句的最佳实践

Python 中的 if 语句是实现条件分支的基本结构,对代码的可读性和可维护性有重大影响。在这里,我们将详细讨论使用 if 语句的最佳实践。

使用明确的条件表达式

简洁明确地编写条件表达式,避免冗余语句。

1condition = True
2
3### Bad Example
4if condition == True:
5    pass
6
7### Good Example
8if condition:
9    pass
  • 在 Python 中,可以通过编写 if condition: 表示条件为真。

组合多个条件

组合多个条件时,请使用 andor。然而,当条件表达式变得复杂时,可读性可能会降低,因此请考虑如下调整:。

 1age = 15
 2is_student = True
 3
 4### Bad Example
 5# Complex condition
 6if (age > 18 and age < 65) or (is_student and age > 15):
 7    pass
 8
 9### Good Example
10# Improving readability
11is_working_age = 18 < age < 65
12is_eligible_student = is_student and age > 15
13
14if is_working_age or is_eligible_student:
15    pass
  • 通过将条件拆分并分配给变量,可以提高可读性。

and/or 短路求值

在使用 andor 的条件表达式中,如果结果仅由左侧的值决定,就会发生短路求值,右侧的表达式将不会被计算。理解这一点有助于你避免不必要的处理和预防错误。

 1user = None
 2def expensive_check():
 3    return True
 4
 5# Example of short-circuiting with 'and'
 6if user and user.is_active:
 7    # If user is None, user.is_active will NOT be evaluated
 8    print("Active user found.")
 9
10# Example of short-circuiting with 'or'
11if user.is_admin or expensive_check(user):
12    # If user.is_admin is True, expensive_check will NOT be called.
13    print("Access granted.")
14else:
15    print("Access denied.")
  • 利用短路求值,可以提高处理效率和安全性。

andor 的优先级

and 的优先级高于 or。因此,如果直接组合条件,可能会得到非预期的结果。使用括号明确表达意图非常重要。

 1age = 15
 2is_student = True
 3
 4### Unclear example
 5# This is interpreted as: age > 18 and (age < 65 or is_student)
 6if age > 18 and age < 65 or is_student:
 7    pass
 8
 9### Clear example
10# Explicit parentheses make the intended logic obvious
11if (age > 18 and age < 65) or is_student:
12    pass
  • 通过使用括号,可以明确 andor 的优先级,降低出现意外 bug 的风险。

理解 Truthy 和 Falsy

在 Python 中,以下值会被评估为 False:。

  • 数字 0(包括 0.0
  • 空序列类型(如空列表、元组或字符串)
    • 示例:[]()""
  • 空字典
    • 示例:{}

利用这一点可以简化条件表达式。

1items = [1, 2, 3]
2
3### Bad Example
4if len(items) > 0:
5    pass
6
7### Good Example
8if items:
9    pass

正确使用 elifelse

评估多个条件时,使用 elif。使用 else 在末尾定义默认行为。

 1score = 80
 2
 3if score >= 90:
 4    grade = "A"
 5elif score >= 80:
 6    grade = "B"
 7elif score >= 70:
 8    grade = "C"
 9else:
10    grade = "F"
  • else 不是强制性的。如果涵盖了所有条件,可以省略。
  • 注意条件表达式的顺序,逻辑安排避免冗余。

限制嵌套的深度。

if 语句的深度嵌套会使代码更难阅读。

 1def access_resource():
 2    return True
 3
 4### Bad Example
 5def deep_nest(user, resource):
 6    if user.is_authenticated:
 7        if user.has_permission:
 8            if resource.is_available:
 9                access_resource()
10
11### Good Example
12def early_return(user, resource):
13    if not user.is_authenticated:
14        return
15    if not user.has_permission:
16        return
17    if not resource.is_available:
18        return
19
20    access_resource()
  • 使用提前返回可以减少嵌套,使代码更加简洁。

避免使用单行 if 语句。

可以将if语句写在一行,但这样可能会降低可读性。

 1condition = False
 2def do_something():
 3    return True
 4
 5### Bad Example
 6if condition: do_something()
 7
 8### Good Example
 9if condition:
10    do_something()
  • 单行if语句仅适用于简短的条件或操作,但应避免写出过于冗长的代码。

用三元运算符或 or 简化

对于简单的条件分支,使用三元运算符或 or 可以让代码更加简洁。但如果滥用这些方法,会让代码更加难以阅读,因此只应在简单直观的条件下使用。

 1is_admin = True
 2input_name = None
 3
 4# Regular if statement
 5if is_admin:
 6    role = "Administrator"
 7else:
 8    role = "User"
 9
10# Simplified using an inline if
11role = "Administrator" if is_admin else "User"
12
13# Use 'or' to provide a default value
14name = input_name or "Guest"
  • 对于简单条件,使用三元运算符或 or 可以让代码更短、更易理解。

缓存条件表达式。

包含高成本计算或函数调用的条件表达式可以缓存到变量中以提高性能。

 1def expensive_function():
 2    pass
 3
 4def another_expensive_function():
 5    pass
 6
 7### Bad Example
 8if expensive_function() and another_expensive_function():
 9    pass
10
11### Good Example
12result1 = expensive_function()
13result2 = another_expensive_function()
14if result1 and result2:
15    pass

总结

Python 的 if 语句是简单而强大的工具,但使用不当会使代码变得复杂且难以阅读。通过采用此处介绍的最佳实践,您可以提高代码的可读性、可维护性和效率。

您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。

YouTube Video