Python 條件語句的最佳實踐

Python 條件語句的最佳實踐

本文將介紹 Python 條件語句的最佳實踐。

YouTube Video

Python 條件語句的最佳實踐

if 語句是 Python 中實現條件分支的基本結構,對代碼的可讀性和可維護性有著重要影響。在這裡,我們將詳細討論如何使用 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