Functions và Error Handling
1. Định nghĩa Functions
1.1 Basic Function
Python
1# Định nghĩa function2def greet(name):3 """Chào người dùng - đây là docstring"""4 return f"Hello, {name}!"56# Gọi function7message = greet("MinAI")8print(message) # Hello, MinAI!910# Function không có return11def print_info(name, age):12 print(f"Name: {name}")13 print(f"Age: {age}")14 # Tự động return None1.2 Parameters
Python
1# Default parameters2def greet(name, greeting="Hello"):3 return f"{greeting}, {name}!"45greet("Alice") # "Hello, Alice!"6greet("Alice", "Hi") # "Hi, Alice!"78# Keyword arguments9def create_profile(name, age, city):10 return {"name": name, "age": age, "city": city}1112# Có thể gọi theo bất kỳ thứ tự13profile = create_profile(age=25, city="Hanoi", name="Bob")1415# *args - Nhận nhiều positional arguments16def sum_all(*args):17 return sum(args)1819sum_all(1, 2, 3, 4, 5) # 152021# **kwargs - Nhận nhiều keyword arguments22def build_dict(**kwargs):23 return kwargs2425build_dict(a=1, b=2, c=3) # {'a': 1, 'b': 2, 'c': 3}2627# Kết hợp28def func(a, b, *args, **kwargs):29 print(f"a={a}, b={b}")30 print(f"args={args}")31 print(f"kwargs={kwargs}")3233func(1, 2, 3, 4, x=10, y=20)34# a=1, b=235# 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)45# Unpacking6min_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.0910# Hoặc nhận tuple11stats = 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: expression23# Function thường4def square(x):5 return x ** 267# Lambda tương đương8square = lambda x: x ** 2910# Sử dụng11print(square(5)) # 251213# Lambda với nhiều arguments14add = lambda x, y: x + y15print(add(3, 4)) # 71617# Lambda thường dùng với map, filter, sorted18numbers = [1, 2, 3, 4, 5]1920# 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]2324# filter - lọc phần tử25evens = list(filter(lambda x: x % 2 == 0, numbers))26# [2, 4]2728# sorted - sắp xếp với key29students = [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 time4 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 result10 return wrapper1112# Sử dụng decorator13@timer14def slow_function():15 import time16 time.sleep(1)17 return "Done!"1819slow_function()20# slow_function took 1.0012 seconds3.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 result8 return wrapper9 return decorator1011@repeat(times=3)12def say_hello(name):13 print(f"Hello, {name}!")1415say_hello("World")16# Hello, World!17# Hello, World!18# Hello, World!3.3 Common Decorators
Python
1from functools import lru_cache23# Caching - Lưu kết quả để không tính lại4@lru_cache(maxsize=128)5def fibonacci(n):6 if n < 2:7 return n8 return fibonacci(n-1) + fibonacci(n-2)910print(fibonacci(100)) # Rất nhanh nhờ cache!1112# Property decorator13class Circle:14 def __init__(self, radius):15 self._radius = radius16 17 @property18 def radius(self):19 return self._radius20 21 @radius.setter22 def radius(self, value):23 if value < 0:24 raise ValueError("Radius must be positive")25 self._radius = value26 27 @property28 def area(self):29 import math30 return math.pi * self._radius ** 23132circle = Circle(5)33print(circle.area) # 78.539...4. Error Handling
4.1 Try-Except
Python
1# Basic try-except2try:3 result = 10 / 04except ZeroDivisionError:5 print("Cannot divide by zero!")67# Multiple exceptions8try:9 num = int(input("Enter a number: "))10 result = 10 / num11except ValueError:12 print("Invalid input - not a number!")13except ZeroDivisionError:14 print("Cannot divide by zero!")1516# Catch all exceptions17try:18 risky_operation()19except Exception as e:20 print(f"Error occurred: {e}")2122# else and finally23try: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ỗi30 print(f"File content: {content}")31finally:32 # Luôn luôn chạy33 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 True78# Custom Exception9class 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_code1415def 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 data2122# Sử dụng23try: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 with2with open("data.txt", "r") as file:3 content = file.read()4# File tự động đóng sau khi ra khỏi with block56# Custom context manager7class Timer:8 def __enter__(self):9 import time10 self.start = time.time()11 return self12 13 def __exit__(self, *args):14 import time15 self.end = time.time()16 print(f"Elapsed: {self.end - self.start:.4f}s")1718with Timer():19 # Code cần đo thời gian20 sum([i**2 for i in range(1000000)])21# Elapsed: 0.1234s5. Built-in Functions Hữu Ích
5.1 Iteration Functions
Python
1numbers = [1, 2, 3, 4, 5]23# map - transform4squares = list(map(lambda x: x**2, numbers))56# filter - lọc7evens = list(filter(lambda x: x % 2 == 0, numbers))89# reduce - aggregate10from functools import reduce11total = reduce(lambda x, y: x + y, numbers) # 151213# zip - kết hợp14names = ["Alice", "Bob"]15scores = [85, 90]16combined = list(zip(names, scores)) # [("Alice", 85), ("Bob", 90)]1718# enumerate - index + value19for idx, val in enumerate(numbers):20 print(f"{idx}: {val}")2122# any, all23any([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]23len(numbers) # 84sum(numbers) # 315min(numbers) # 16max(numbers) # 97sorted(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]89# abs, round, pow10abs(-5) # 511round(3.14159, 2) # 3.1412pow(2, 10) # 10241314# isinstance, type15isinstance(5, int) # True16type([1, 2, 3]) # <class 'list'>6. Modules và Imports
6.1 Import Methods
Python
1# Import toàn bộ module2import math3print(math.sqrt(16)) # 4.045# Import với alias6import pandas as pd7import numpy as np89# Import specific functions10from math import sqrt, pi11print(sqrt(16)) # 4.01213# Import all (không khuyến khích)14from math import *6.2 Tạo Module
Python
1# utils.py2def calculate_mean(numbers):3 return sum(numbers) / len(numbers)45def calculate_std(numbers):6 mean = calculate_mean(numbers)7 variance = sum((x - mean)**2 for x in numbers) / len(numbers)8 return variance ** 0.5910# main.py11from utils import calculate_mean, calculate_std1213data = [1, 2, 3, 4, 5]14print(calculate_mean(data)) # 3.015print(calculate_std(data)) # 1.414...6.3 name == "main"
Python
1# my_module.py2def main():3 print("Running as main script")45def helper():6 return "Helper function"78# Chỉ chạy khi file được execute trực tiếp9if __name__ == "__main__":10 main()1112# Khi import: main() không tự động chạy13# from my_module import helperTổ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!
