Lý thuyết
Bài 4/14

Functions và Error Handling

Định nghĩa functions, lambda, decorators và xử lý lỗi trong Python

Functions và Error Handling

1. Định nghĩa Functions

1.1 Basic Function

Python
1# Định nghĩa function
2def greet(name):
3 """Chào người dùng - đây là docstring"""
4 return f"Hello, {name}!"
5
6# Gọi function
7message = greet("MinAI")
8print(message) # Hello, MinAI!
9
10# Function không có return
11def print_info(name, age):
12 print(f"Name: {name}")
13 print(f"Age: {age}")
14 # Tự động return None

1.2 Parameters

Python
1# Default parameters
2def greet(name, greeting="Hello"):
3 return f"{greeting}, {name}!"
4
5greet("Alice") # "Hello, Alice!"
6greet("Alice", "Hi") # "Hi, Alice!"
7
8# Keyword arguments
9def create_profile(name, age, city):
10 return {"name": name, "age": age, "city": city}
11
12# Có thể gọi theo bất kỳ thứ tự
13profile = create_profile(age=25, city="Hanoi", name="Bob")
14
15# *args - Nhận nhiều positional arguments
16def sum_all(*args):
17 return sum(args)
18
19sum_all(1, 2, 3, 4, 5) # 15
20
21# **kwargs - Nhận nhiều keyword arguments
22def build_dict(**kwargs):
23 return kwargs
24
25build_dict(a=1, b=2, c=3) # {'a': 1, 'b': 2, 'c': 3}
26
27# Kết hợp
28def func(a, b, *args, **kwargs):
29 print(f"a={a}, b={b}")
30 print(f"args={args}")
31 print(f"kwargs={kwargs}")
32
33func(1, 2, 3, 4, x=10, y=20)
34# a=1, b=2
35# args=(3, 4)
36# kwargs={'x': 10, 'y': 20}

1.3 Return Multiple Values

Python
1def get_stats(numbers):
2 """Tính các thống kê cơ bản"""
3 return min(numbers), max(numbers), sum(numbers)/len(numbers)
4
5# Unpacking
6min_val, max_val, avg = get_stats([1, 2, 3, 4, 5])
7print(f"Min: {min_val}, Max: {max_val}, Avg: {avg}")
8# Min: 1, Max: 5, Avg: 3.0
9
10# Hoặc nhận tuple
11stats = get_stats([1, 2, 3, 4, 5])
12print(stats) # (1, 5, 3.0)

2. Lambda Functions

Lambda là anonymous function - function không tên, viết trên 1 dòng.

Python
1# Cú pháp: lambda arguments: expression
2
3# Function thường
4def square(x):
5 return x ** 2
6
7# Lambda tương đương
8square = lambda x: x ** 2
9
10# Sử dụng
11print(square(5)) # 25
12
13# Lambda với nhiều arguments
14add = lambda x, y: x + y
15print(add(3, 4)) # 7
16
17# Lambda thường dùng với map, filter, sorted
18numbers = [1, 2, 3, 4, 5]
19
20# map - áp dụng function cho từng phần tử
21squares = list(map(lambda x: x**2, numbers))
22# [1, 4, 9, 16, 25]
23
24# filter - lọc phần tử
25evens = list(filter(lambda x: x % 2 == 0, numbers))
26# [2, 4]
27
28# sorted - sắp xếp với key
29students = [
30 {"name": "Alice", "score": 85},
31 {"name": "Bob", "score": 92},
32 {"name": "Charlie", "score": 78}
33]
34sorted_students = sorted(students, key=lambda x: x["score"], reverse=True)
35# Bob (92), Alice (85), Charlie (78)

3. Decorators

Decorator là function "bọc" function khác để thêm chức năng.

3.1 Basic Decorator

Python
1def timer(func):
2 """Decorator đo thời gian chạy"""
3 import time
4 def wrapper(*args, **kwargs):
5 start = time.time()
6 result = func(*args, **kwargs)
7 end = time.time()
8 print(f"{func.__name__} took {end-start:.4f} seconds")
9 return result
10 return wrapper
11
12# Sử dụng decorator
13@timer
14def slow_function():
15 import time
16 time.sleep(1)
17 return "Done!"
18
19slow_function()
20# slow_function took 1.0012 seconds

3.2 Decorator với parameters

Python
1def repeat(times):
2 """Decorator chạy function nhiều lần"""
3 def decorator(func):
4 def wrapper(*args, **kwargs):
5 for _ in range(times):
6 result = func(*args, **kwargs)
7 return result
8 return wrapper
9 return decorator
10
11@repeat(times=3)
12def say_hello(name):
13 print(f"Hello, {name}!")
14
15say_hello("World")
16# Hello, World!
17# Hello, World!
18# Hello, World!

3.3 Common Decorators

Python
1from functools import lru_cache
2
3# Caching - Lưu kết quả để không tính lại
4@lru_cache(maxsize=128)
5def fibonacci(n):
6 if n < 2:
7 return n
8 return fibonacci(n-1) + fibonacci(n-2)
9
10print(fibonacci(100)) # Rất nhanh nhờ cache!
11
12# Property decorator
13class Circle:
14 def __init__(self, radius):
15 self._radius = radius
16
17 @property
18 def radius(self):
19 return self._radius
20
21 @radius.setter
22 def radius(self, value):
23 if value < 0:
24 raise ValueError("Radius must be positive")
25 self._radius = value
26
27 @property
28 def area(self):
29 import math
30 return math.pi * self._radius ** 2
31
32circle = Circle(5)
33print(circle.area) # 78.539...

4. Error Handling

4.1 Try-Except

Python
1# Basic try-except
2try:
3 result = 10 / 0
4except ZeroDivisionError:
5 print("Cannot divide by zero!")
6
7# Multiple exceptions
8try:
9 num = int(input("Enter a number: "))
10 result = 10 / num
11except ValueError:
12 print("Invalid input - not a number!")
13except ZeroDivisionError:
14 print("Cannot divide by zero!")
15
16# Catch all exceptions
17try:
18 risky_operation()
19except Exception as e:
20 print(f"Error occurred: {e}")
21
22# else and finally
23try:
24 file = open("data.txt", "r")
25 content = file.read()
26except FileNotFoundError:
27 print("File not found!")
28else:
29 # Chạy nếu không có lỗi
30 print(f"File content: {content}")
31finally:
32 # Luôn luôn chạy
33 print("Cleanup done")

4.2 Raise Exceptions

Python
1def validate_age(age):
2 if age < 0:
3 raise ValueError("Age cannot be negative")
4 if age > 150:
5 raise ValueError("Age seems unrealistic")
6 return True
7
8# Custom Exception
9class InvalidDataError(Exception):
10 """Exception cho dữ liệu không hợp lệ"""
11 def __init__(self, message, error_code=None):
12 super().__init__(message)
13 self.error_code = error_code
14
15def process_data(data):
16 if not data:
17 raise InvalidDataError("Data is empty", error_code=1001)
18 if not isinstance(data, dict):
19 raise InvalidDataError("Data must be dictionary", error_code=1002)
20 return data
21
22# Sử dụng
23try:
24 process_data([])
25except InvalidDataError as e:
26 print(f"Error: {e}, Code: {e.error_code}")

4.3 Context Manager (with statement)

Python
1# File handling với with
2with open("data.txt", "r") as file:
3 content = file.read()
4# File tự động đóng sau khi ra khỏi with block
5
6# Custom context manager
7class Timer:
8 def __enter__(self):
9 import time
10 self.start = time.time()
11 return self
12
13 def __exit__(self, *args):
14 import time
15 self.end = time.time()
16 print(f"Elapsed: {self.end - self.start:.4f}s")
17
18with Timer():
19 # Code cần đo thời gian
20 sum([i**2 for i in range(1000000)])
21# Elapsed: 0.1234s

5. Built-in Functions Hữu Ích

5.1 Iteration Functions

Python
1numbers = [1, 2, 3, 4, 5]
2
3# map - transform
4squares = list(map(lambda x: x**2, numbers))
5
6# filter - lọc
7evens = list(filter(lambda x: x % 2 == 0, numbers))
8
9# reduce - aggregate
10from functools import reduce
11total = reduce(lambda x, y: x + y, numbers) # 15
12
13# zip - kết hợp
14names = ["Alice", "Bob"]
15scores = [85, 90]
16combined = list(zip(names, scores)) # [("Alice", 85), ("Bob", 90)]
17
18# enumerate - index + value
19for idx, val in enumerate(numbers):
20 print(f"{idx}: {val}")
21
22# any, all
23any([False, True, False]) # True (có ít nhất 1 True)
24all([True, True, False]) # False (không phải tất cả True)

5.2 Data Functions

Python
1numbers = [3, 1, 4, 1, 5, 9, 2, 6]
2
3len(numbers) # 8
4sum(numbers) # 31
5min(numbers) # 1
6max(numbers) # 9
7sorted(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
8
9# abs, round, pow
10abs(-5) # 5
11round(3.14159, 2) # 3.14
12pow(2, 10) # 1024
13
14# isinstance, type
15isinstance(5, int) # True
16type([1, 2, 3]) # <class 'list'>

6. Modules và Imports

6.1 Import Methods

Python
1# Import toàn bộ module
2import math
3print(math.sqrt(16)) # 4.0
4
5# Import với alias
6import pandas as pd
7import numpy as np
8
9# Import specific functions
10from math import sqrt, pi
11print(sqrt(16)) # 4.0
12
13# Import all (không khuyến khích)
14from math import *

6.2 Tạo Module

Python
1# utils.py
2def calculate_mean(numbers):
3 return sum(numbers) / len(numbers)
4
5def calculate_std(numbers):
6 mean = calculate_mean(numbers)
7 variance = sum((x - mean)**2 for x in numbers) / len(numbers)
8 return variance ** 0.5
9
10# main.py
11from utils import calculate_mean, calculate_std
12
13data = [1, 2, 3, 4, 5]
14print(calculate_mean(data)) # 3.0
15print(calculate_std(data)) # 1.414...

6.3 name == "main"

Python
1# my_module.py
2def main():
3 print("Running as main script")
4
5def helper():
6 return "Helper function"
7
8# Chỉ chạy khi file được execute trực tiếp
9if __name__ == "__main__":
10 main()
11
12# Khi import: main() không tự động chạy
13# from my_module import helper

Tổng Kết

Trong bài này, bạn đã học:

  • ✅ Định nghĩa và gọi functions
  • ✅ Parameters: args, kwargs, defaults
  • ✅ Lambda functions và ứng dụng
  • ✅ Decorators và cách tạo
  • ✅ Error handling với try-except
  • ✅ Built-in functions quan trọng
  • ✅ Modules và imports

Bài tiếp theo: NumPy - Nền tảng tính toán số học trong Python!