🎯 Mục tiêu bài học
Sau bài học này, bạn sẽ:
✅ Thành thạo Control Flow: if/elif/else, for, while, list comprehension
✅ Sử dụng được Collections: List, Dictionary, Set, Tuple
✅ Viết Functions với parameters, *args, **kwargs, return values
✅ Hiểu Lambda, Decorators và Error Handling
Thời gian: 3 giờ | Độ khó: Beginner | Yêu cầu: Hoàn thành Bài 1
📖 Bảng Thuật Ngữ Quan Trọng
| Thuật ngữ | Tiếng Việt | Giải thích đơn giản |
|---|---|---|
| Control Flow | Luồng điều khiển | Quyết định code nào chạy dựa trên điều kiện |
| Loop | Vòng lặp | Lặp lại một đoạn code nhiều lần |
| List Comprehension | Tạo list rút gọn | Cách viết ngắn gọn tạo list: [x**2 for x in range(5)] |
| Dictionary | Từ điển | Cấu trúc lưu cặp key-value: {"name": "Alice"} |
| Function | Hàm | Khối code tái sử dụng, nhận input trả output |
| Lambda | Hàm ẩn danh | Function không tên, viết trên 1 dòng |
| Decorator | Bộ trang trí | Function bọc function khác để thêm chức năng |
| Exception | Ngoại lệ | Lỗi xảy ra khi chạy chương trình |
| try-except | Xử lý lỗi | Bắt và xử lý lỗi thay vì crash chương trình |
| Module | Mô-đun | File Python chứa code có thể import và tái sử dụng |
Checkpoint
Bạn đã đọc qua bảng thuật ngữ chưa? Hãy quay lại đây khi gặp thuật ngữ lạ trong bài!
🔀 Control Flow
Control Flow (Luồng điều khiển) là gì? Bình thường Python chạy code từ trên xuống dưới, tuần tự. Nhưng trong thực tế, bạn cần:
- Ra quyết định: "Nếu khách VIP thì giảm 20%, không thì giảm 5%" → dùng if/else
- Lặp lại: "Tính tổng doanh thu cho từng tháng" → dùng for loop
- Chờ điều kiện: "Tiếp tục hỏi password cho đến khi đúng" → dùng while loop
If-Elif-Else
Câu lệnh điều kiện cho phép chương trình ra quyết định — giống như chọn đường đi dựa trên thời tiết: trời mưa → mang ô, trời nắng → đội mũ, bình thường → đi tay không.
Cú pháp: if kiểm tra điều kiện → đúng thì chạy code bên trong, sai thì bỏ qua. elif kiểm tra điều kiện tiếp. else chạy khi tất cả điều kiện trên đều sai.
1score = 8523if score >= 90:4 grade = "A"5elif score >= 80:6 grade = "B"7elif score >= 70:8 grade = "C"9else:10 grade = "F"1112print(f"Grade: {grade}") # Grade: B1314# Ternary operator (one-line if)15status = "Pass" if score >= 60 else "Fail"For Loop
Vòng lặp for là gì? Vòng lặp cho phép bạn lặp lại một thao tác cho nhiều phần tử — giống như đi chợ với danh sách mua sắm: lần lượt đi qua từng món, cho vào giỏ, rồi qua món tiếp theo.
Tại sao cần vòng lặp? Thay vì viết 1000 dòng print() riêng biệt, bạn chỉ cần 2 dòng for loop. Trong DS: duyệt từng file CSV, xử lý từng cột, tính toán cho từng nhóm khách hàng...
1# Iterate over list2fruits = ["apple", "banana", "cherry"]3for fruit in fruits:4 print(fruit)56# Range7for i in range(5): # 0, 1, 2, 3, 48 print(i)9for i in range(1, 6): # 1, 2, 3, 4, 510 print(i)11for i in range(0, 10, 2): # 0, 2, 4, 6, 812 print(i)1314# Enumerate (index + value)15for idx, fruit in enumerate(fruits):16 print(f"{idx}: {fruit}")1718# Zip (parallel iteration)19names = ["Alice", "Bob"]20ages = [25, 30]21for name, age in zip(names, ages):22 print(f"{name} is {age}")Giải thích các pattern quan trọng:
range(n): Tạo dãy số từ 0 đến n-1. Dùng khi biết chính xác cần lặp bao nhiêu lần.enumerate(): Lấy cả index lẫn giá trị — rất hữu ích khi cần biết đang ở vị trí thứ mấy.zip(): Duyệt song song 2+ list — ví dụ: ghép tên sinh viên với điểm số.
While Loop
Vòng lặp while chạy liên tục cho đến khi điều kiện sai. Khác với for (biết trước số lần lặp), while dùng khi không biết cần lặp bao nhiêu lần — ví dụ: yêu cầu nhập lại password cho đến khi đúng, tải dữ liệu cho đến khi hết trang.
1count = 02while count < 5:3 print(count)4 count += 156# break và continue7while True:8 user_input = input("Enter 'q' to quit: ")9 if user_input == 'q':10 break # Thoát vòng lặp11 if user_input == '':12 continue # Bỏ qua, lặp tiếp13 print(f"You entered: {user_input}")break và continue:
break: Dừng hẳn vòng lặp — ví dụ: tìm thấy kết quả rồi, không cần tìm tiếp.continue: Bỏ qua lần lặp hiện tại, nhảy sang lần tiếp — ví dụ: bỏ qua dữ liệu trống.
List Comprehension
List Comprehension là cách viết "Pythonic" — ngắn gọn và nhanh hơn vòng for thông thường. Đây là pattern rất phổ biến trong Data Science!
1# Basic2squares = [x**2 for x in range(10)]3# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]45# With condition (filter)6evens = [x for x in range(20) if x % 2 == 0]7# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]89# Nested10matrix = [[i*j for j in range(3)] for i in range(3)]11# [[0,0,0], [0,1,2], [0,2,4]]1213# Dict comprehension14squares_dict = {x: x**2 for x in range(5)}15# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}1617# Set comprehension18unique_lengths = {len(word) for word in ["hello", "world", "hi"]}19# {2, 5}Checkpoint
Viết list comprehension tạo danh sách các số chia hết cho 3 trong khoảng 1-50. Kết quả bao nhiêu phần tử?
📚 Collections
Collections là các cấu trúc dữ liệu dùng để lưu nhiều giá trị trong một biến. Python có 4 loại chính — mỗi loại phù hợp với mục đích khác nhau:
| Collection | Đặc điểm | Khi nào dùng? | Ví dụ |
|---|---|---|---|
List [] | Có thứ tự, thay đổi được | Danh sách dữ liệu chung | Điểm các bài thi, sản phẩm |
Dict {} | Cặp key-value | Tra cứu nhanh theo tên | Thông tin khách hàng, config |
Set {} | Không trùng lặp | Tìm giá trị duy nhất | Danh sách thành phố, tags |
Tuple () | Không thay đổi được | Dữ liệu cố định | Tọa độ (x, y), return nhiều giá trị |
List
List (danh sách) là collection phổ biến nhất — giống như một hàng đợi có thể thêm, xóa, sắp xếp tùy ý:
1# Create2fruits = ["apple", "banana", "cherry"]3numbers = list(range(1, 6))45# Access6fruits[0] # "apple"7fruits[-1] # "cherry"8fruits[1:3] # ["banana", "cherry"]910# Modify11fruits.append("orange") # Add to end12fruits.insert(1, "grape") # Insert at index13fruits.extend(["kiwi"]) # Add multiple items14fruits.remove("banana") # Remove by value15fruits.pop() # Remove & return last16fruits.pop(0) # Remove & return by index1718# Other methods19fruits.sort() # Sort in place20fruits.reverse() # Reverse in place21fruits.index("apple") # Find index22fruits.count("apple") # Count occurrences23len(fruits) # LengthDictionary
1# Create2person = {3 "name": "Alice",4 "age": 25,5 "city": "Hanoi"6}78# Access9person["name"] # "Alice"10person.get("name") # "Alice"11person.get("job", "N/A") # "N/A" (default if key missing)1213# Modify14person["age"] = 26 # Update15person["job"] = "Data Scientist" # Add new key1617# Methods18person.keys() # dict_keys(['name', 'age', 'city', 'job'])19person.values() # dict_values(['Alice', 26, 'Hanoi', 'Data Scientist'])20person.items() # dict_items([('name', 'Alice'), ...])2122# Iterate23for key, value in person.items():24 print(f"{key}: {value}")Dictionary là cấu trúc dữ liệu quan trọng nhất trong Python — dùng khắp nơi: JSON data, function kwargs, config, API responses...
Set & Tuple
Set chỉ chứa giá trị không trùng lặp — rất hữu ích khi muốn tìm "có bao nhiêu giá trị khác nhau?" (ví dụ: bao nhiêu thành phố trong dataset?).
Tuple giống List nhưng không thể thay đổi sau khi tạo — dùng khi dữ liệu không nên bị sửa (tọa độ GPS, return nhiều giá trị từ function).
1# Set - Unique values, unordered2colors = {"red", "green", "blue"}3colors.add("yellow")4colors.remove("red")56# Set operations (rất hữu ích cho Data Science!)7a = {1, 2, 3}8b = {2, 3, 4}9print(a | b) # Union: {1, 2, 3, 4}10print(a & b) # Intersection: {2, 3}11print(a - b) # Difference: {1}1213# Tuple - Immutable list (không thể thay đổi)14point = (10, 20)15x, y = point # Unpacking1617# Practical: return multiple values18def get_min_max(numbers):19 return min(numbers), max(numbers) # Returns tuple2021lo, hi = get_min_max([3, 1, 4, 1, 5])Checkpoint
Tạo một dictionary chứa thông tin 3 sinh viên (tên, điểm). Dùng dict comprehension để lọc ra sinh viên có điểm >= 8.
🔧 Functions
Function (hàm) là gì? Function là một khối code có tên, nhận input → xử lý → trả output. Hãy tưởng tượng function như một công thức nấu ăn: đưa nguyên liệu vào (parameters), làm theo các bước (code), và nhận món ăn hoàn chỉnh (return value).
Tại sao cần function?
- Tái sử dụng: Viết 1 lần, dùng nhiều lần — không cần copy-paste
- Dễ đọc:
calculate_bmi(70, 1.75)rõ ràng hơn 10 dòng tính toán - Dễ sửa: Sửa 1 chỗ, áp dụng cho mọi nơi gọi function
- DRY Principle: Don't Repeat Yourself — nguyên tắc vàng trong lập trình
Basic Function
1def greet(name):2 """Chào người dùng - đây là docstring"""3 return f"Hello, {name}!"45message = greet("MinAI")6print(message) # Hello, MinAI!Parameters
1# Default parameters2def greet(name, greeting="Hello"):3 return f"{greeting}, {name}!"45greet("Alice") # "Hello, Alice!"6greet("Alice", "Hi") # "Hi, Alice!"78# Keyword arguments (gọi theo bất kỳ thứ tự)9def create_profile(name, age, city):10 return {"name": name, "age": age, "city": city}1112profile = create_profile(age=25, city="Hanoi", name="Bob")1314# *args - Nhận số lượng arguments KHÔNG CỐ ĐỊNH15# Ví dụ: sum_all(1, 2) hoặc sum_all(1, 2, 3, 4, 5) — đều được!16def sum_all(*args):17 return sum(args)1819sum_all(1, 2, 3, 4, 5) # 152021# **kwargs - Nhận keyword arguments KHÔNG CỐ ĐỊNH22# Ví dụ: build_dict(name="Alice", age=25) — gọi với bất kỳ keyword nào23def build_dict(**kwargs):24 return kwargs2526build_dict(a=1, b=2, c=3) # {'a': 1, 'b': 2, 'c': 3}2728# Kết hợp tất cả29def func(a, b, *args, **kwargs):30 print(f"a={a}, b={b}")31 print(f"args={args}")32 print(f"kwargs={kwargs}")3334func(1, 2, 3, 4, x=10, y=20)35# a=1, b=2 | args=(3, 4) | kwargs={'x': 10, 'y': 20}Return Multiple Values
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}")Checkpoint
Viết function calculate_bmi(weight, height) nhận cân nặng (kg) và chiều cao (m), trả về BMI và phân loại ("Gầy"/"Bình thường"/"Thừa cân").
⚡ Lambda và Built-in Functions
Lambda Functions
Lambda là anonymous function — function không tên, viết trên 1 dòng.
1# Function thường vs Lambda2def square(x):3 return x ** 245square = lambda x: x ** 2 # Tương đương67# Lambda với nhiều arguments8add = lambda x, y: x + yỨng dụng với map, filter, sorted
Ba built-in functions này kết hợp với lambda tạo thành pattern rất mạnh:
map(func, list): Áp dụng func cho từng phần tử → list mới (ví dụ: đổi đơn vị cho cả cột)filter(func, list): Lọc chỉ giữ phần tử thỏa điều kiện (ví dụ: lọc khách có đơn hàng)sorted(list, key=func): Sắp xếp theo tiêu chí tùy chọn (ví dụ: sắp theo điểm cao → thấp)
1numbers = [1, 2, 3, 4, 5]23# map - áp dụng function cho từng phần tử4squares = list(map(lambda x: x**2, numbers))5# [1, 4, 9, 16, 25]67# filter - lọc phần tử8evens = list(filter(lambda x: x % 2 == 0, numbers))9# [2, 4]1011# sorted - sắp xếp với key12students = [13 {"name": "Alice", "score": 85},14 {"name": "Bob", "score": 92},15 {"name": "Charlie", "score": 78}16]17sorted_students = sorted(students, key=lambda x: x["score"], reverse=True)18# Bob (92), Alice (85), Charlie (78)Built-in Functions hữu ích
1numbers = [3, 1, 4, 1, 5, 9, 2, 6]23# Aggregation4len(numbers) # 85sum(numbers) # 316min(numbers) # 17max(numbers) # 98sorted(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]910# Logic11any([False, True, False]) # True (ít nhất 1 True)12all([True, True, False]) # False (không phải tất cả)1314# Math15abs(-5) # 516round(3.14159, 2) # 3.1417pow(2, 10) # 10241819# reduce - aggregate tuần tự20from functools import reduce21total = reduce(lambda x, y: x + y, numbers) # 31Trong Data Science, bạn sẽ dùng lambda rất nhiều với Pandas: df['col'].apply(lambda x: x * 2), df.sort_values(key=lambda x: ...).
Checkpoint
Dùng filter + lambda để lọc ra các từ có độ dài > 4 từ list ["hi", "hello", "world", "ok", "python"].
🎨 Decorators
Decorator là function "bọc" function khác để thêm chức năng — rất phổ biến trong Python.
Basic Decorator
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@timer13def slow_function():14 import time15 time.sleep(1)16 return "Done!"1718slow_function()19# slow_function took 1.0012 secondsDecorator với parameters
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! (3 lần)Common Decorators
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 area(self):19 import math20 return math.pi * self._radius ** 22122circle = Circle(5)23print(circle.area) # 78.539...Decorator bạn sẽ gặp thường xuyên khi làm việc với Flask/FastAPI (@app.route), testing (@pytest.fixture), và caching (@lru_cache).
Checkpoint
@timer decorator hoạt động ra sao? Nó nhận function gốc, bọc trong wrapper, đo thời gian trước/sau khi gọi function gốc.
🛡️ Error Handling
Try-Except
1# Basic2try: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 + else + finally17try:18 file = open("data.txt", "r")19 content = file.read()20except FileNotFoundError:21 print("File not found!")22else:23 print(f"File content: {content}") # Chạy nếu KHÔNG có lỗi24finally:25 print("Cleanup done") # LUÔN LUÔN chạyRaise & Custom Exceptions
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 def __init__(self, message, error_code=None):11 super().__init__(message)12 self.error_code = error_code1314def process_data(data):15 if not data:16 raise InvalidDataError("Data is empty", error_code=1001)17 return dataContext Manager (with)
1# File handling — tự động đóng file2with open("data.txt", "r") as file:3 content = file.read()4# File tự động đóng 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 sum([i**2 for i in range(1000000)])Quan trọng: Luôn dùng with khi làm việc với file. Nếu không, file có thể không được đóng đúng cách, gây rò rỉ tài nguyên.
Checkpoint
Viết function an toàn: nhận string, trả về int — nếu không convert được thì trả về 0. Dùng try-except.
📦 Modules và Imports
Import Methods
1# Import toàn bộ module2import math3print(math.sqrt(16)) # 4.045# Import với alias (rất phổ biến trong Data Science)6import pandas as pd7import numpy as np8import matplotlib.pyplot as plt910# Import specific functions11from math import sqrt, pi12print(sqrt(16)) # 4.0Tạo Module riêng
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_std12data = [1, 2, 3, 4, 5]13print(calculate_mean(data)) # 3.0__name__ == "__main__"
1# my_module.py2def main():3 print("Running as main script")45if __name__ == "__main__":6 main() # Chỉ chạy khi execute trực tiếp, không chạy khi importCheckpoint
Tại sao Data Science luôn dùng alias import pandas as pd? Để code ngắn gọn hơn: pd.read_csv() thay vì pandas.read_csv().
📝 Tổng Kết
Câu hỏi tự kiểm tra
- List comprehension khác gì so với vòng lặp
forthông thường? Khi nào nên dùng list comprehension? - Sự khác biệt giữa
*argsvà**kwargstrong định nghĩa function là gì? - Tại sao nên dùng
with open()thay vìopen()vàclose()riêng lẻ khi xử lý file? - Dictionary và List khác nhau như thế nào? Khi nào nên dùng Dictionary thay vì List?
✅ Những điều bạn đã học được
- 🔀 Control Flow — if/elif/else, for loop, while loop, list comprehension
- 📚 Collections — List, Dictionary, Set, Tuple và methods quan trọng
- 🔧 Functions — Parameters, *args, **kwargs, return, docstrings
- ⚡ Lambda — Anonymous functions, map/filter/sorted
- 🎨 Decorators — @timer, @lru_cache, @property
- 🛡️ Error Handling — try/except/else/finally, raise, custom exceptions
- 📦 Modules — import, alias, tạo module riêng
Bài tập tự luyện
- Viết function
flatten(nested_list)biến[[1,2],[3,4],[5]]thành[1,2,3,4,5]dùng list comprehension - Tạo dict
word_countđếm số lần xuất hiện mỗi từ trong câu"the cat sat on the mat the cat" - Viết decorator
@login ra tên function và arguments mỗi khi gọi - Viết function đọc file CSV an toàn — trả về data nếu thành công,
Nonenếu file không tồn tại
Bài tiếp theo: Bài tập thực hành Python Basics — Practice makes perfect! 💪
