Học Python Từ Zero Trong 7 Ngày (Có Ví Dụ Thực Tế)

Học Python Từ Zero Trong 7 Ngày (Có Ví Dụ Thực Tế)

Học Python Từ Zero Trong 7 Ngày: Lộ Trình Chi Tiết Với Ví Dụ Thực Tế

Python là một trong những ngôn ngữ lập trình phổ biến nhất hiện nay, được sử dụng rộng rãi trong nhiều lĩnh vực như web development, data science, machine learning, automation, và nhiều hơn nữa. Với cú pháp đơn giản, dễ học, và cộng đồng lớn, Python là lựa chọn lý tưởng cho những người mới bắt đầu học lập trình. Trong bài viết này, chúng ta sẽ cùng nhau học Python từ zero trong 7 ngày với lộ trình chi tiết và các ví dụ thực tế giúp bạn nắm vững kiến thức cơ bản.

Giới Thiệu Về Python

Python được tạo ra bởi Guido van Rossum và được phát hành lần đầu vào năm 1991. Ngôn ngữ này được thiết kế với triết lý "Code is read more often than it is written", nhấn mạnh vào tính dễ đọc và dễ hiểu của code. Python sử dụng indentation (thụt lề) để xác định khối code thay vì dùng dấu ngoặc nhọn như nhiều ngôn ngữ khác, điều này làm cho code Python trở nên sạch sẽ và dễ đọc hơn.

Python là ngôn ngữ interpreted (thông dịch), có nghĩa là code được thực thi trực tiếp mà không cần biên dịch trước. Điều này giúp quá trình development nhanh hơn và dễ dàng test code. Python cũng là ngôn ngữ đa mục đích, có thể được sử dụng để phát triển nhiều loại ứng dụng khác nhau, từ script đơn giản đến ứng dụng web phức tạp, từ data analysis đến machine learning.

Một trong những điểm mạnh lớn nhất của Python là hệ sinh thái thư viện phong phú. Với PyPI (Python Package Index), bạn có thể dễ dàng cài đặt hàng nghìn thư viện để hỗ trợ các tác vụ khác nhau, từ web development (Django, Flask) đến data science (Pandas, NumPy) và machine learning (TensorFlow, PyTorch).

Ngày 1: Cài Đặt Python và Làm Quen Với Cú Pháp Cơ Bản

1.1 Cài Đặt Python

Bước đầu tiên để học Python là cài đặt Python trên máy tính của bạn. Python có sẵn cho Windows, macOS, và Linux. Bạn có thể tải Python từ trang web chính thức python.org. Hiện tại, Python 3.x là phiên bản được khuyến nghị sử dụng, vì Python 2.x đã không còn được hỗ trợ từ năm 2020.

Sau khi cài đặt Python, bạn có thể kiểm tra phiên bản bằng cách mở terminal (Command Prompt trên Windows, Terminal trên macOS/Linux) và chạy lệnh:

python --version
# Hoặc
python3 --version

Bạn cũng nên cài đặt một code editor hoặc IDE để viết code Python. Một số lựa chọn phổ biến bao gồm:

  • Visual Studio Code (VS Code): Miễn phí, nhẹ, và có nhiều extension hỗ trợ Python
  • PyCharm: IDE chuyên dụng cho Python với nhiều tính năng mạnh mẽ
  • Sublime Text: Editor nhẹ và nhanh
  • Jupyter Notebook: Tuyệt vời cho data science và experimentation

1.2 Chương Trình Hello World Đầu Tiên

Bắt đầu với chương trình cổ điển "Hello, World!":

print("Hello, World!")
print("Chào mừng bạn đến với Python!")

Trong Python, hàm print() được sử dụng để in ra màn hình. Bạn có thể in nhiều giá trị cùng lúc:

print("Tên:", "Nguyễn Văn A")
print("Tuổi:", 25)
print("Nghề nghiệp:", "Developer")

1.3 Comments và Documentation

Comments giúp code dễ hiểu hơn. Trong Python, bạn sử dụng dấu # để tạo comment một dòng:

# Đây là một comment
print("Hello")  # Comment ở cuối dòng

# Comment nhiều dòng
# Dòng 1
# Dòng 2
# Dòng 3

Đối với documentation string (docstring), bạn sử dụng ba dấu ngoặc kép:

"""
Đây là docstring
Có thể viết nhiều dòng
Giải thích về chương trình hoặc hàm
"""

1.4 Biến và Kiểu Dữ Liệu Cơ Bản

Trong Python, bạn không cần khai báo kiểu dữ liệu khi tạo biến. Python tự động xác định kiểu dữ liệu dựa trên giá trị bạn gán:

# Số nguyên (integer)
age = 25
count = 100

# Số thực (float)
price = 99.99
temperature = 36.5

# Chuỗi (string)
name = "Nguyễn Văn A"
message = "Xin chào"

# Boolean
is_student = True
is_working = False

# None (giá trị rỗng)
data = None

Ví dụ thực tế 1: Tính toán đơn giản

# Tính tiền mua hàng
so_luong = 5
gia_moi_san_pham = 150000
tong_tien = so_luong * gia_moi_san_pham
thue_vat = tong_tien * 0.1
tong_thanh_toan = tong_tien + thue_vat

print(f"Số lượng: {so_luong}")
print(f"Giá mỗi sản phẩm: {gia_moi_san_pham:,} VNĐ")
print(f"Tổng tiền: {tong_tien:,} VNĐ")
print(f"Thuế VAT (10%): {thue_vat:,} VNĐ")
print(f"Tổng thanh toán: {tong_thanh_toan:,} VNĐ")

1.5 Nhập Dữ Liệu Từ Người Dùng

Hàm input() cho phép bạn nhận dữ liệu từ người dùng:

name = input("Nhập tên của bạn: ")
age = input("Nhập tuổi của bạn: ")

print(f"Xin chào {name}, bạn {age} tuổi.")

Lưu ý: Hàm input() luôn trả về chuỗi. Nếu bạn muốn nhận số, cần chuyển đổi:

age = int(input("Nhập tuổi: "))
price = float(input("Nhập giá: "))

Ví dụ thực tế 2: Máy tính đơn giản

print("=== MÁY TÍNH ĐỀN GIẢN ===")
so_thu_nhat = float(input("Nhập số thứ nhất: "))
so_thu_hai = float(input("Nhập số thứ hai: "))

tong = so_thu_nhat + so_thu_hai
hieu = so_thu_nhat - so_thu_hai
tich = so_thu_nhat * so_thu_hai
thuong = so_thu_nhat / so_thu_hai if so_thu_hai != 0 else "Không thể chia cho 0"

print(f"\nKết quả:")
print(f"{so_thu_nhat} + {so_thu_hai} = {tong}")
print(f"{so_thu_nhat} - {so_thu_hai} = {hieu}")
print(f"{so_thu_nhat} * {so_thu_hai} = {tich}")
print(f"{so_thu_nhat} / {so_thu_hai} = {thuong}")

Ngày 2: Cấu Trúc Điều Khiển và Vòng Lặp

2.1 Câu Lệnh If, Elif, Else

Câu lệnh điều kiện cho phép bạn thực hiện các hành động khác nhau dựa trên điều kiện:

age = 20

if age < 18:
    print("Bạn là trẻ vị thành niên")
elif age < 65:
    print("Bạn là người trưởng thành")
else:
    print("Bạn là người cao tuổi")

Ví dụ thực tế 3: Kiểm tra điểm số

diem = float(input("Nhập điểm số (0-10): "))

if diem >= 9:
    xep_loai = "Xuất sắc"
elif diem >= 8:
    xep_loai = "Giỏi"
elif diem >= 7:
    xep_loai = "Khá"
elif diem >= 5:
    xep_loai = "Trung bình"
else:
    xep_loai = "Yếu"

print(f"Điểm: {diem} - Xếp loại: {xep_loai}")

2.2 Vòng Lặp For

Vòng lặp for được sử dụng để lặp qua một chuỗi (list, tuple, string, etc.):

# Lặp qua chuỗi
for char in "Python":
    print(char)

# Lặp qua dãy số
for i in range(5):
    print(f"Số: {i}")

# Lặp với range có bước nhảy
for i in range(0, 10, 2):
    print(i)  # In ra 0, 2, 4, 6, 8

Ví dụ thực tế 4: In bảng cửu chương

so = int(input("Nhập số để in bảng cửu chương: "))
print(f"\nBảng cửu chương {so}:")
print("-" * 30)

for i in range(1, 11):
    ket_qua = so * i
    print(f"{so} x {i} = {ket_qua}")

2.3 Vòng Lặp While

Vòng lặp while thực hiện một khối code lặp đi lặp lại chừng nào điều kiện còn đúng:

count = 0
while count < 5:
    print(f"Lần lặp: {count}")
    count += 1

Ví dụ thực tế 5: Chương trình đoán số

import random

so_bi_mat = random.randint(1, 100)
so_lan_doan = 0
so_lan_toi_da = 7

print("Chào mừng đến với trò chơi đoán số!")
print("Tôi đang nghĩ đến một số từ 1 đến 100.")
print(f"Bạn có {so_lan_toi_da} lần để đoán.\n")

while so_lan_doan < so_lan_toi_da:
    so_lan_doan += 1
    doan = int(input(f"Lần đoán thứ {so_lan_doan}: "))
    
    if doan == so_bi_mat:
        print(f"Chúc mừng! Bạn đã đoán đúng sau {so_lan_doan} lần!")
        break
    elif doan < so_bi_mat:
        print("Số của bạn nhỏ hơn số bí mật.")
    else:
        print("Số của bạn lớn hơn số bí mật.")
    
    if so_lan_doan < so_lan_toi_da:
        print(f"Còn lại {so_lan_toi_da - so_lan_doan} lần đoán.\n")

if so_lan_doan >= so_lan_toi_da and doan != so_bi_mat:
    print(f"\nGame Over! Số bí mật là {so_bi_mat}.")

2.4 Break và Continue

break dừng vòng lặp hoàn toàn, continue bỏ qua lần lặp hiện tại:

# Sử dụng break
for i in range(10):
    if i == 5:
        break
    print(i)  # In ra 0, 1, 2, 3, 4

# Sử dụng continue
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)  # In ra các số lẻ: 1, 3, 5, 7, 9

Ngày 3: Danh Sách, Tuple, Dictionary và Set

3.1 List (Danh Sách)

List là một cấu trúc dữ liệu có thứ tự, có thể chứa các phần tử trùng lặp và có thể thay đổi:

# Tạo list
fruits = ["táo", "chuối", "cam", "nho"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# Truy cập phần tử
print(fruits[0])  # "táo"
print(fruits[-1])  # "nho" (phần tử cuối)

# Thêm phần tử
fruits.append("dứa")
fruits.insert(1, "ổi")

# Xóa phần tử
fruits.remove("chuối")
del fruits[0]

# Slicing
print(fruits[1:3])  # Lấy phần tử từ index 1 đến 2
print(fruits[:2])   # Lấy 2 phần tử đầu
print(fruits[2:])   # Lấy từ index 2 đến cuối

Ví dụ thực tế 6: Quản lý danh sách sinh viên

danh_sach_sinh_vien = []

while True:
    print("\n=== QUẢN LÝ SINH VIÊN ===")
    print("1. Thêm sinh viên")
    print("2. Hiển thị danh sách")
    print("3. Tìm kiếm sinh viên")
    print("4. Xóa sinh viên")
    print("5. Thoát")
    
    lua_chon = input("Chọn chức năng (1-5): ")
    
    if lua_chon == "1":
        ten = input("Nhập tên sinh viên: ")
        danh_sach_sinh_vien.append(ten)
        print(f"Đã thêm {ten} vào danh sách.")
    
    elif lua_chon == "2":
        if danh_sach_sinh_vien:
            print("\nDanh sách sinh viên:")
            for i, sv in enumerate(danh_sach_sinh_vien, 1):
                print(f"{i}. {sv}")
        else:
            print("Danh sách trống.")
    
    elif lua_chon == "3":
        ten_tim = input("Nhập tên cần tìm: ")
        if ten_tim in danh_sach_sinh_vien:
            print(f"Tìm thấy {ten_tim} trong danh sách.")
        else:
            print("Không tìm thấy.")
    
    elif lua_chon == "4":
        if danh_sach_sinh_vien:
            ten_xoa = input("Nhập tên cần xóa: ")
            if ten_xoa in danh_sach_sinh_vien:
                danh_sach_sinh_vien.remove(ten_xoa)
                print(f"Đã xóa {ten_xoa}.")
            else:
                print("Không tìm thấy.")
        else:
            print("Danh sách trống.")
    
    elif lua_chon == "5":
        print("Cảm ơn bạn đã sử dụng chương trình!")
        break
    
    else:
        print("Lựa chọn không hợp lệ!")

3.2 Tuple

Tuple giống như list nhưng không thể thay đổi (immutable):

# Tạo tuple
coordinates = (10, 20)
colors = ("đỏ", "xanh", "vàng")

# Truy cập phần tử
print(coordinates[0])  # 10

# Tuple không thể thay đổi
# coordinates[0] = 5  # Lỗi!

# Tuple unpacking
x, y = coordinates
print(f"x = {x}, y = {y}")

3.3 Dictionary (Từ Điển)

Dictionary lưu trữ dữ liệu dưới dạng key-value pairs:

# Tạo dictionary
student = {
    "tên": "Nguyễn Văn A",
    "tuổi": 20,
    "điểm": 8.5,
    "lớp": "12A"
}

# Truy cập giá trị
print(student["tên"])
print(student.get("tuổi", "Không có"))

# Thêm hoặc cập nhật
student["email"] = "[email protected]"
student["tuổi"] = 21

# Xóa
del student["lớp"]

# Lặp qua dictionary
for key, value in student.items():
    print(f"{key}: {value}")

Ví dụ thực tế 7: Quản lý sản phẩm

san_pham = {
    "SP001": {"tên": "Laptop", "giá": 15000000, "số lượng": 10},
    "SP002": {"tên": "Điện thoại", "giá": 8000000, "số lượng": 20},
    "SP003": {"tên": "Tablet", "giá": 5000000, "số lượng": 15}
}

def hien_thi_san_pham():
    print("\n=== DANH SÁCH SẢN PHẨM ===")
    for ma, info in san_pham.items():
        print(f"Mã: {ma}")
        print(f"  Tên: {info["tên"]}")
        print(f"  Giá: {info["giá"]:,} VNĐ")
        print(f"  Số lượng: {info["số lượng"]}")
        print()

def them_san_pham():
    ma = input("Nhập mã sản phẩm: ")
    ten = input("Nhập tên sản phẩm: ")
    gia = int(input("Nhập giá: "))
    so_luong = int(input("Nhập số lượng: "))
    
    san_pham[ma] = {
        "tên": ten,
        "giá": gia,
        "số lượng": so_luong
    }
    print("Đã thêm sản phẩm thành công!")

def tim_kiem_san_pham():
    ma = input("Nhập mã sản phẩm cần tìm: ")
    if ma in san_pham:
        info = san_pham[ma]
        print(f"\nThông tin sản phẩm:")
        print(f"Mã: {ma}")
        print(f"Tên: {info["tên"]}")
        print(f"Giá: {info["giá"]:,} VNĐ")
        print(f"Số lượng: {info["số lượng"]}")
    else:
        print("Không tìm thấy sản phẩm!")

# Menu chính
while True:
    print("\n=== QUẢN LÝ SẢN PHẨM ===")
    print("1. Hiển thị danh sách")
    print("2. Thêm sản phẩm")
    print("3. Tìm kiếm sản phẩm")
    print("4. Thoát")
    
    lua_chon = input("Chọn chức năng: ")
    
    if lua_chon == "1":
        hien_thi_san_pham()
    elif lua_chon == "2":
        them_san_pham()
    elif lua_chon == "3":
        tim_kiem_san_pham()
    elif lua_chon == "4":
        break
    else:
        print("Lựa chọn không hợp lệ!")

3.4 Set

Set là một collection không có thứ tự, không chứa phần tử trùng lặp:

# Tạo set
fruits = {"táo", "chuối", "cam"}
numbers = {1, 2, 3, 4, 5}

# Thêm phần tử
fruits.add("nho")

# Xóa phần tử
fruits.remove("chuối")

# Các phép toán tập hợp
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

print(set1.union(set2))      # {1, 2, 3, 4, 5, 6}
print(set1.intersection(set2))  # {3, 4}
print(set1.difference(set2))    # {1, 2}

Ngày 4: Hàm (Functions) và Modules

4.1 Định Nghĩa Hàm

Hàm giúp tổ chức code thành các khối có thể tái sử dụng:

def greet(name):
    """Hàm chào hỏi"""
    return f"Xin chào, {name}!"

# Gọi hàm
message = greet("Nguyễn Văn A")
print(message)

Ví dụ thực tế 8: Hàm tính toán

def tinh_diem_trung_binh(danh_sach_diem):
    """Tính điểm trung bình từ danh sách điểm"""
    if not danh_sach_diem:
        return 0
    return sum(danh_sach_diem) / len(danh_sach_diem)

def xep_loai_hoc_sinh(diem_trung_binh):
    """Xếp loại học sinh dựa trên điểm trung bình"""
    if diem_trung_binh >= 9:
        return "Xuất sắc"
    elif diem_trung_binh >= 8:
        return "Giỏi"
    elif diem_trung_binh >= 7:
        return "Khá"
    elif diem_trung_binh >= 5:
        return "Trung bình"
    else:
        return "Yếu"

# Sử dụng
diem_mon_hoc = [8.5, 7.5, 9.0, 8.0, 7.0]
diem_tb = tinh_diem_trung_binh(diem_mon_hoc)
xep_loai = xep_loai_hoc_sinh(diem_tb)

print(f"Điểm trung bình: {diem_tb:.2f}")
print(f"Xếp loại: {xep_loai}")

4.2 Tham Số Mặc Định và Tham Số Tùy Chọn

def introduce(name, age=18, city="Hà Nội"):
    """Giới thiệu với tham số mặc định"""
    return f"Tôi là {name}, {age} tuổi, đến từ {city}"

print(introduce("Nguyễn Văn A"))
print(introduce("Trần Thị B", 25))
print(introduce("Lê Văn C", 30, "TP.HCM"))

4.3 *args và **kwargs

def sum_numbers(*args):
    """Tính tổng nhiều số"""
    return sum(args)

def print_info(**kwargs):
    """In thông tin với keyword arguments"""
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print(sum_numbers(1, 2, 3, 4, 5))
print_info(tên="Nguyễn Văn A", tuổi=25, nghề="Developer")

4.4 Lambda Functions

# Lambda function
square = lambda x: x ** 2
print(square(5))  # 25

# Sử dụng với map, filter
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
even = list(filter(lambda x: x % 2 == 0, numbers))

print(squared)  # [1, 4, 9, 16, 25]
print(even)     # [2, 4]

4.5 Modules và Import

Modules cho phép bạn tổ chức code thành các file riêng biệt:

# File: math_utils.py
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

# File: main.py
import math_utils

result = math_utils.add(5, 3)
print(result)

Ví dụ thực tế 9: Module quản lý thời gian

# File: time_utils.py
import datetime

def get_current_time():
    """Lấy thời gian hiện tại"""
    return datetime.datetime.now()

def format_date(date, format_string="%d/%m/%Y"):
    """Định dạng ngày tháng"""
    return date.strftime(format_string)

def calculate_age(birth_date):
    """Tính tuổi từ ngày sinh"""
    today = datetime.date.today()
    return today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))

# Sử dụng
from time_utils import get_current_time, format_date, calculate_age

now = get_current_time()
print(f"Thời gian hiện tại: {format_date(now)}")

birth = datetime.date(2000, 1, 1)
age = calculate_age(birth)
print(f"Tuổi: {age}")

Ngày 5: Xử Lý File và Exception Handling

5.1 Đọc và Ghi File

# Ghi file
with open("data.txt", "w", encoding="utf-8") as f:
    f.write("Dòng 1\n")
    f.write("Dòng 2\n")
    f.write("Dòng 3\n")

# Đọc file
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

# Đọc từng dòng
with open("data.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

Ví dụ thực tế 10: Quản lý ghi chú

import os

FILE_NAME = "notes.txt"

def load_notes():
    """Tải danh sách ghi chú từ file"""
    if os.path.exists(FILE_NAME):
        with open(FILE_NAME, "r", encoding="utf-8") as f:
            return [line.strip() for line in f.readlines()]
    return []

def save_notes(notes):
    """Lưu danh sách ghi chú vào file"""
    with open(FILE_NAME, "w", encoding="utf-8") as f:
        for note in notes:
            f.write(note + "\n")

def add_note(notes):
    """Thêm ghi chú mới"""
    note = input("Nhập ghi chú: ")
    notes.append(note)
    save_notes(notes)
    print("Đã thêm ghi chú thành công!")

def view_notes(notes):
    """Xem danh sách ghi chú"""
    if notes:
        print("\n=== DANH SÁCH GHI CHÚ ===")
        for i, note in enumerate(notes, 1):
            print(f"{i}. {note}")
    else:
        print("Chưa có ghi chú nào.")

def delete_note(notes):
    """Xóa ghi chú"""
    view_notes(notes)
    if notes:
        index = int(input("Nhập số thứ tự ghi chú cần xóa: ")) - 1
        if 0 <= index < len(notes):
            deleted = notes.pop(index)
            save_notes(notes)
            print(f"Đã xóa: {deleted}")
        else:
            print("Số thứ tự không hợp lệ!")

# Chương trình chính
notes = load_notes()

while True:
    print("\n=== QUẢN LÝ GHI CHÚ ===")
    print("1. Thêm ghi chú")
    print("2. Xem ghi chú")
    print("3. Xóa ghi chú")
    print("4. Thoát")
    
    choice = input("Chọn chức năng: ")
    
    if choice == "1":
        add_note(notes)
    elif choice == "2":
        view_notes(notes)
    elif choice == "3":
        delete_note(notes)
    elif choice == "4":
        break
    else:
        print("Lựa chọn không hợp lệ!")

5.2 Exception Handling

try:
    number = int(input("Nhập một số: "))
    result = 10 / number
    print(f"Kết quả: {result}")
except ValueError:
    print("Lỗi: Bạn phải nhập một số nguyên!")
except ZeroDivisionError:
    print("Lỗi: Không thể chia cho 0!")
except Exception as e:
    print(f"Lỗi: {e}")
finally:
    print("Kết thúc chương trình.")

Ví dụ thực tế 11: Xử lý lỗi khi đọc file

def read_file_safe(filename):
    """Đọc file an toàn với xử lý lỗi"""
    try:
        with open(filename, "r", encoding="utf-8") as f:
            content = f.read()
            return content
    except FileNotFoundError:
        print(f"Lỗi: Không tìm thấy file {filename}")
        return None
    except PermissionError:
        print(f"Lỗi: Không có quyền đọc file {filename}")
        return None
    except Exception as e:
        print(f"Lỗi không xác định: {e}")
        return None

# Sử dụng
content = read_file_safe("data.txt")
if content:
    print(content)

Ngày 6: Lập Trình Hướng Đối Tượng (OOP)

6.1 Class và Object

class Student:
    """Class đại diện cho sinh viên"""
    
    def __init__(self, name, age, student_id):
        """Constructor - khởi tạo đối tượng"""
        self.name = name
        self.age = age
        self.student_id = student_id
        self.grades = []
    
    def add_grade(self, grade):
        """Thêm điểm"""
        self.grades.append(grade)
    
    def get_average(self):
        """Tính điểm trung bình"""
        if self.grades:
            return sum(self.grades) / len(self.grades)
        return 0
    
    def display_info(self):
        """Hiển thị thông tin"""
        print(f"Tên: {self.name}")
        print(f"Tuổi: {self.age}")
        print(f"Mã SV: {self.student_id}")
        print(f"Điểm TB: {self.get_average():.2f}")

# Tạo đối tượng
student1 = Student("Nguyễn Văn A", 20, "SV001")
student1.add_grade(8.5)
student1.add_grade(7.5)
student1.add_grade(9.0)
student1.display_info()

Ví dụ thực tế 12: Hệ thống quản lý thư viện

class Book:
    """Class đại diện cho sách"""
    
    def __init__(self, title, author, isbn):
        self.title = title
        self.author = author
        self.isbn = isbn
        self.is_borrowed = False
    
    def borrow(self):
        """Mượn sách"""
        if self.is_borrowed:
            return False
        self.is_borrowed = True
        return True
    
    def return_book(self):
        """Trả sách"""
        self.is_borrowed = False
    
    def __str__(self):
        status = "Đã mượn" if self.is_borrowed else "Có sẵn"
        return f"{self.title} - {self.author} ({status})"

class Library:
    """Class quản lý thư viện"""
    
    def __init__(self):
        self.books = []
    
    def add_book(self, book):
        """Thêm sách vào thư viện"""
        self.books.append(book)
        print(f"Đã thêm sách: {book.title}")
    
    def find_book(self, title):
        """Tìm sách theo tên"""
        for book in self.books:
            if book.title.lower() == title.lower():
                return book
        return None
    
    def borrow_book(self, title):
        """Mượn sách"""
        book = self.find_book(title)
        if book:
            if book.borrow():
                print(f"Đã mượn sách: {book.title}")
            else:
                print(f"Sách {book.title} đã được mượn.")
        else:
            print("Không tìm thấy sách.")
    
    def return_book(self, title):
        """Trả sách"""
        book = self.find_book(title)
        if book:
            book.return_book()
            print(f"Đã trả sách: {book.title}")
        else:
            print("Không tìm thấy sách.")
    
    def display_books(self):
        """Hiển thị danh sách sách"""
        print("\n=== DANH SÁCH SÁCH ===")
        for book in self.books:
            print(book)

# Sử dụng
library = Library()

library.add_book(Book("Python Programming", "John Doe", "ISBN001"))
library.add_book(Book("Data Science", "Jane Smith", "ISBN002"))
library.add_book(Book("Machine Learning", "Bob Johnson", "ISBN003"))

library.display_books()
library.borrow_book("Python Programming")
library.display_books()

6.2 Inheritance (Kế Thừa)

class Animal:
    """Class cơ sở"""
    
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        return "Animal makes a sound"

class Dog(Animal):
    """Class con kế thừa từ Animal"""
    
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    """Class con kế thừa từ Animal"""
    
    def speak(self):
        return f"{self.name} says Meow!"

# Sử dụng
dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak())
print(cat.speak())

Ngày 7: Dự Án Thực Tế - Ứng Dụng Quản Lý Tài Chính Cá Nhân

Trong ngày cuối cùng, chúng ta sẽ xây dựng một ứng dụng quản lý tài chính cá nhân hoàn chỉnh, tích hợp tất cả các kiến thức đã học:

import json
import os
from datetime import datetime

class Transaction:
    """Class đại diện cho một giao dịch"""
    
    def __init__(self, amount, category, description, transaction_type):
        self.amount = amount
        self.category = category
        self.description = description
        self.transaction_type = transaction_type  # "income" hoặc "expense"
        self.date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    def to_dict(self):
        """Chuyển đổi thành dictionary để lưu vào file"""
        return {
            "amount": self.amount,
            "category": self.category,
            "description": self.description,
            "type": self.transaction_type,
            "date": self.date
        }
    
    @classmethod
    def from_dict(cls, data):
        """Tạo Transaction từ dictionary"""
        transaction = cls(
            data["amount"],
            data["category"],
            data["description"],
            data["type"]
        )
        transaction.date = data["date"]
        return transaction
    
    def __str__(self):
        type_str = "Thu nhập" if self.transaction_type == "income" else "Chi tiêu"
        return f"{self.date} - {type_str}: {self.amount:,} VNĐ - {self.category} - {self.description}"

class FinanceManager:
    """Class quản lý tài chính"""
    
    def __init__(self, filename="finance_data.json"):
        self.filename = filename
        self.transactions = self.load_transactions()
        self.balance = self.calculate_balance()
    
    def load_transactions(self):
        """Tải danh sách giao dịch từ file"""
        if os.path.exists(self.filename):
            try:
                with open(self.filename, "r", encoding="utf-8") as f:
                    data = json.load(f)
                    return [Transaction.from_dict(t) for t in data]
            except Exception as e:
                print(f"Lỗi khi đọc file: {e}")
                return []
        return []
    
    def save_transactions(self):
        """Lưu danh sách giao dịch vào file"""
        try:
            with open(self.filename, "w", encoding="utf-8") as f:
                data = [t.to_dict() for t in self.transactions]
                json.dump(data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"Lỗi khi lưu file: {e}")
    
    def add_transaction(self, amount, category, description, transaction_type):
        """Thêm giao dịch mới"""
        transaction = Transaction(amount, category, description, transaction_type)
        self.transactions.append(transaction)
        self.save_transactions()
        self.balance = self.calculate_balance()
        print("Đã thêm giao dịch thành công!")
    
    def calculate_balance(self):
        """Tính số dư hiện tại"""
        balance = 0
        for transaction in self.transactions:
            if transaction.transaction_type == "income":
                balance += transaction.amount
            else:
                balance -= transaction.amount
        return balance
    
    def get_income(self):
        """Tính tổng thu nhập"""
        return sum(t.amount for t in self.transactions if t.transaction_type == "income")
    
    def get_expenses(self):
        """Tính tổng chi tiêu"""
        return sum(t.amount for t in self.transactions if t.transaction_type == "expense")
    
    def get_expenses_by_category(self):
        """Thống kê chi tiêu theo danh mục"""
        categories = {}
        for transaction in self.transactions:
            if transaction.transaction_type == "expense":
                if transaction.category in categories:
                    categories[transaction.category] += transaction.amount
                else:
                    categories[transaction.category] = transaction.amount
        return categories
    
    def display_summary(self):
        """Hiển thị tổng quan tài chính"""
        income = self.get_income()
        expenses = self.get_expenses()
        balance = self.balance
        
        print("\n=== TỔNG QUAN TÀI CHÍNH ===")
        print(f"Tổng thu nhập: {income:,} VNĐ")
        print(f"Tổng chi tiêu: {expenses:,} VNĐ")
        print(f"Số dư hiện tại: {balance:,} VNĐ")
        
        if expenses > 0:
            expense_ratio = (expenses / income * 100) if income > 0 else 0
            print(f"Tỷ lệ chi tiêu: {expense_ratio:.2f}%")
    
    def display_transactions(self):
        """Hiển thị danh sách giao dịch"""
        if not self.transactions:
            print("Chưa có giao dịch nào.")
            return
        
        print("\n=== DANH SÁCH GIAO DỊCH ===")
        for i, transaction in enumerate(self.transactions, 1):
            print(f"{i}. {transaction}")
    
    def display_expenses_by_category(self):
        """Hiển thị chi tiêu theo danh mục"""
        categories = self.get_expenses_by_category()
        if not categories:
            print("Chưa có chi tiêu nào.")
            return
        
        print("\n=== CHI TIÊU THEO DANH MỤC ===")
        for category, amount in sorted(categories.items(), key=lambda x: x[1], reverse=True):
            print(f"{category}: {amount:,} VNĐ")

def main():
    """Hàm chính của chương trình"""
    manager = FinanceManager()
    
    while True:
        print("\n=== QUẢN LÝ TÀI CHÍNH CÁ NHÂN ===")
        print("1. Thêm thu nhập")
        print("2. Thêm chi tiêu")
        print("3. Xem tổng quan")
        print("4. Xem danh sách giao dịch")
        print("5. Xem chi tiêu theo danh mục")
        print("6. Thoát")
        
        choice = input("Chọn chức năng (1-6): ")
        
        if choice == "1":
            amount = int(input("Nhập số tiền: "))
            category = input("Nhập danh mục: ")
            description = input("Nhập mô tả: ")
            manager.add_transaction(amount, category, description, "income")
        
        elif choice == "2":
            amount = int(input("Nhập số tiền: "))
            category = input("Nhập danh mục: ")
            description = input("Nhập mô tả: ")
            manager.add_transaction(amount, category, description, "expense")
        
        elif choice == "3":
            manager.display_summary()
        
        elif choice == "4":
            manager.display_transactions()
        
        elif choice == "5":
            manager.display_expenses_by_category()
        
        elif choice == "6":
            print("Cảm ơn bạn đã sử dụng chương trình!")
            break
        
        else:
            print("Lựa chọn không hợp lệ!")

if __name__ == "__main__":
    main()

Kết Luận và Bước Tiếp Theo

Sau 7 ngày học Python, bạn đã nắm được các kiến thức cơ bản về:

  • Cú pháp Python và các kiểu dữ liệu cơ bản
  • Cấu trúc điều khiển và vòng lặp
  • Danh sách, tuple, dictionary, và set
  • Hàm và modules
  • Xử lý file và exception handling
  • Lập trình hướng đối tượng (OOP)
  • Xây dựng ứng dụng thực tế

Bước tiếp theo để tiếp tục học Python:

  1. Practice thường xuyên: Viết code mỗi ngày, giải các bài tập lập trình
  2. Tham gia cộng đồng: Tham gia các forum, group Python để học hỏi và chia sẻ
  3. Đọc code của người khác: Học từ các project trên GitHub
  4. Xây dựng projects: Tạo các dự án thực tế để áp dụng kiến thức
  5. Học thư viện: Tìm hiểu các thư viện phổ biến như Pandas (data science), Flask/Django (web), Requests (HTTP)
  6. Tham gia khóa học: Tham gia các khóa học online hoặc offline để nâng cao kỹ năng
  7. Python là một ngôn ngữ mạnh mẽ và linh hoạt. Với nền tảng vững chắc sau 7 ngày học, bạn đã sẵn sàng để tiếp tục khám phá và phát triển kỹ năng lập trình Python của mình. Chúc bạn thành công trên hành trình học Python!

← Về trang chủ Xem thêm bài viết Lập Trình →