3分鐘掌握 Python 中的函數

Python 中的函數

1. 功能介紹

Python 中的函數是執行特定任務或一組任務的代碼塊。函數接受輸入參數、執行操作並返回結果。它們使用關鍵字定義,後跟函數名稱和一對括號。def

def greet(name):
  """This function greets the person passes in a parameter"""
  print(f"Hello, {name}!")

#Calling the function
greet("Alice")


2. 函數參數和返回值

函數可以採用多個參數,也可以返回值。參數是調用函數時將傳遞給函數的值的佔位符。

def add(a, b):
  """This function adds two numbers."""
  return a + b

result = add(3, 5)
print(result)  #Output: 8

在這裡,該函數採用兩個參數和 ,並返回它們的總和。然後打印結果。addab

函數的基本概念

1. 默認參數

在 Python 中,您可以為參數分配默認值,在調用函數時使其成為可選值。

def power(base, exponent=2)
  """This function calculates the power of a number with a default exponent of 2."""
  return base ** exponent

result1 = power(2)    #Equivalent to power(2, 2)
result2 = power(2, 3)

print(result1)    #Output: 4
print(result2)    #Output: 8

在此示例中,該函數的參數默認值為 。當僅使用參數調用函數時,將使用默認值。power2exponentbase

2. 可變長度參數列表

Python 允許您使用 和 定義可以接受可變數量參數的函數。*args**kwargs

def sum_all(*args):
  """This function calculates the sum of all passed arguments."""
  return sum(args)

result = sum_all(1, 2, 3, 4, 5, 6)
print(result)    #Output: 15

在此示例中,該函數用於接受任意數量的位置參數並計算它們的總和。sum_all*args

3. Lambda 函數(匿名函數

Lambda 函數是使用 關鍵字定義的小型匿名函數。lambda

multiply = lambda x, y: x * y
result = multiply(3, 4)
print(result)    #Output: 12

lambda 函數採用兩個參數並返回它們的乘積。Lambda 函數通常用於短期操作。muliply

函數的實際應用

1. 代碼可重用性

函數的主要優點之一是代碼的可重用性。通過將一段功能封裝到一個函數中,可以輕鬆地在整個程序中重用它。

def calculate_area(radius):
  """This function calculates the area of circle."""
  return 3.14 * radius**2

# Calculating the area for two circles
area1 = calculate_area(5)
area2 = calculate_area(8)

print(area1)    #Output: 78.5
print(area2)    #Output: 200.96

在此示例中,該函數允許在不複製代碼的情況下計算具有不同半徑的圓的面積。

2. 抽象和模塊化

函數提供了一種抽象複雜操作和增強模塊化的方法。將程序分解為更小、更易於管理的功能可使代碼庫更易於維護。

def process_data(data):
  """This function processess a list of numbers."""
  result = []
  for number in data:
    processed_number = number * 2 + 5
    result.append(processed_number)
  return result

#Using the function
input_data = [1, 2, 3, 4, 5, 6]
ouput_data = process_data(input_data)

print(output_data)    #Output: [7, 9, 11, 13, 15]

在這裡,該函數封裝了處理數字列表的邏輯,使代碼更加模塊化且更易於理解。

3. 使用函數進行錯誤處理

函數可以通過封裝可能在塊中引發異常的代碼來幫助您進行錯誤處理。try-except

def divide(a, b):
  """This function divides two number and handels division by zero."""
  try:
      result = a / b
      return result
  except ZeroDivisionError:
      print("Error: Cannot divide by zero.")
      return None

#Using th function
result1 = divide(10, 2)
result2 = divide(5, 0)

print(result1)    #Output: 5.0
print(result2)    #Output: None (with an error message)

在此示例中,該函數處理除以零的可能性,從而防止程序崩潰。

編寫函數的方法

1. 函數命名

為函數選擇有意義且具有描述性的名稱。精心選擇的名稱應傳達函數的目的。

# Less descripctive function name
def func1(x, y):
    return x + y

# More descriptive function name
def add_numbers(x, y):
    return x + y

為清楚起見,首選第二個示例,其名稱更具描述性。

2. 單一責任原則

遵循單一責任原則,該原則指出一個函數應該有一個明確的功能。如果一個函數執行多個獲取,請將其分解為更小的函數。

# Function violating the SIngle Responsibility Principle
def process_data_and_print_results(data):
    """This function processess data and prints the results."""
    processed_data = process_data(data)
    print_results(processed_data)

#Better approach: Separate responsibility
def process_data(data):
    """This function processes data."""
    result = []
    for number in data:
        processed_number = number * 2 + 5
        result.append(processed_number)
    return result

def print_results(data):
    """This function prints the results."""
    for result in data:
        print(result)

將責任分解為單獨的功能可增強代碼的可讀性和可維護性。

3. 文檔和注釋

提供文檔和注釋,以解釋函數的用途、預期的參數和返回值。

def calculate_area(radius):
    """
    This function calculates the area of a circle.

    Parameters:
    - radius (float): The radius of the circle.

    Returns:
    float: The area of the circle.
    """

    return 3.14 * radius**2