Skip to content

✅ 4.4 Kiểu logic (bool)

📖 Giới thiệu

Kiểu dữ liệu boolean (bool) chỉ có hai giá trị: True (đúng) hoặc False (sai). Đây là nền tảng của logic trong lập trình, giúp chương trình ra quyết định và điều khiển luồng thực thi.

Mục tiêu bài học:

  • Hiểu kiểu dữ liệu boolean và cách sử dụng
  • Thành thạo các toán tử logic và so sánh
  • Biết cách chuyển đổi các kiểu dữ liệu khác thành bool
  • Ứng dụng boolean trong điều khiển chương trình

🔧 Cú pháp

Khai báo boolean:

python
# Trực tiếp
dung = True
sai = False

# Từ kết quả so sánh
la_hoc_sinh = tuoi < 18
da_tot_nghiep = diem >= 5.0

# Từ hàm trả về boolean
co_email = '@' in email
rong = len(text) == 0

Toán tử logic:

python
# AND - cả hai đều đúng
ket_qua = dieu_kien_1 and dieu_kien_2

# OR - ít nhất một đúng  
ket_qua = dieu_kien_1 or dieu_kien_2

# NOT - đảo ngược
ket_qua = not dieu_kien

Toán tử so sánh:

python
a == b    # Bằng
a != b    # Khác
a < b     # Nhỏ hơn
a > b     # Lớn hơn  
a <= b    # Nhỏ hơn hoặc bằng
a >= b    # Lớn hơn hoặc bằng

🔬 Phân tích & Giải thích chi tiết

1. ✅ Giá trị boolean cơ bản

True và False:

python
# Khai báo trực tiếp
dang_hoc = True
da_ket_thuc = False

print(type(dang_hoc))  # <class 'bool'>
print(dang_hoc)        # True

# Boolean là subclass của int
print(isinstance(True, int))   # True
print(True + False)            # 1 (True=1, False=0)
print(True * 5)                # 5

Chuyển đổi thành boolean:

python
# Các giá trị "falsy" (được coi là False)
print(bool(0))          # False
print(bool(0.0))        # False
print(bool(""))         # False
print(bool([]))         # False (list rỗng)
print(bool({}))         # False (dict rỗng)
print(bool(None))       # False

# Các giá trị "truthy" (được coi là True)
print(bool(1))          # True
print(bool(-1))         # True
print(bool("hello"))    # True
print(bool([1, 2]))     # True (list có phần tử)
print(bool({"a": 1}))   # True (dict có phần tử)

2. 🧮 Toán tử logic

AND (và):

python
# Cả hai điều kiện phải đúng
tuoi = 20
co_bang_lai = True

co_the_lai_xe = (tuoi >= 18) and co_bang_lai
print(co_the_lai_xe)  # True

# Short-circuit evaluation
def func1():
    print("Hàm 1 được gọi")
    return False

def func2():
    print("Hàm 2 được gọi")
    return True

# func2() không được gọi vì func1() đã trả về False
result = func1() and func2()  # Chỉ in "Hàm 1 được gọi"

OR (hoặc):

python
# Ít nhất một điều kiện đúng
la_sinh_vien = True
la_giao_vien = False

duoc_giam_gia = la_sinh_vien or la_giao_vien
print(duoc_giam_gia)  # True

# Short-circuit với OR
result = True or func2()  # func2() không được gọi

NOT (không):

python
# Đảo ngược giá trị boolean
dang_mua = True
khong_mua = not dang_mua
print(khong_mua)  # False

# Với biểu thức
tuoi = 15
khong_phai_nguoi_lon = not (tuoi >= 18)
print(khong_phai_nguoi_lon)  # True

3. 🔍 Toán tử so sánh

So sánh số:

python
a, b = 10, 20

print(a == b)   # False
print(a != b)   # True
print(a < b)    # True
print(a > b)    # False
print(a <= 10)  # True
print(b >= 20)  # True

So sánh chuỗi:

python
# So sánh theo thứ tự lexicographic (từ điển)
print("apple" < "banana")      # True
print("Apple" < "apple")       # True (chữ hoa < chữ thường)
print("10" < "2")              # True (so sánh chuỗi, không phải số)

# So sánh không phân biệt hoa thường
name1 = "Python"
name2 = "python"
print(name1.lower() == name2.lower())  # True

Toán tử membership:

python
# in - kiểm tra có chứa
fruits = ["apple", "banana", "orange"]
print("apple" in fruits)          # True
print("grape" not in fruits)      # True

# Với chuỗi
text = "Hello Python"
print("Python" in text)           # True
print("Java" not in text)         # True

# Với dictionary (kiểm tra key)
person = {"name": "John", "age": 30}
print("name" in person)           # True
print("address" not in person)    # True

4. 🎯 Kết hợp các toán tử

Thứ tự ưu tiên:

python
# 1. not (cao nhất)
# 2. and
# 3. or (thấp nhất)

a, b, c = True, False, True

# Tương đương với: (not b) and (a or c)
result = not b and a or c
print(result)  # True

# Nên dùng dấu ngoặc cho rõ ràng
result = (not b) and (a or c)
print(result)  # True

Biểu thức phức tạp:

python
tuoi = 25
co_kinh_nghiem = True
co_bang_cap = True
luong_mong_muon = 15000000

# Điều kiện tuyển dụng phức tạp
duoc_nhan = (
    (tuoi >= 22 and tuoi <= 35) and
    (co_kinh_nghiem or co_bang_cap) and
    luong_mong_muon <= 20000000
)

print(f"Được nhận việc: {duoc_nhan}")

5. 🔄 Chuyển đổi kiểu và truthy/falsy

Quy tắc chuyển đổi:

python
# Số 0 và 0.0 là False
print(bool(0))      # False
print(bool(0.0))    # False
print(bool(42))     # True
print(bool(-1))     # True

# Chuỗi rỗng là False
print(bool(""))     # False
print(bool(" "))    # True (có khoảng trắng)
print(bool("0"))    # True (chuỗi không rỗng)

# Container rỗng là False
print(bool([]))     # False
print(bool({}))     # False
print(bool(set()))  # False
print(bool([0]))    # True (có phần tử)

# None là False
print(bool(None))   # False

Sử dụng trong điều kiện:

python
# Thay vì
if len(my_list) > 0:
    print("List có phần tử")

# Nên viết
if my_list:
    print("List có phần tử")

# Thay vì  
if text != "":
    print("Có nội dung")

# Nên viết
if text:
    print("Có nội dung")

💻 Ví dụ minh họa

Ví dụ 1: Hệ thống đăng nhập

python
# he_thong_dang_nhap.py
print("🔐 HỆ THỐNG ĐĂNG NHẬP")
print("=" * 30)

# Database giả lập
users_db = {
    "admin": {"password": "admin123", "role": "admin", "active": True},
    "user1": {"password": "pass123", "role": "user", "active": True},
    "user2": {"password": "mypass", "role": "user", "active": False}
}

def kiem_tra_dang_nhap(username, password):
    """Kiểm tra thông tin đăng nhập"""
    # Kiểm tra user có tồn tại
    user_ton_tai = username in users_db
    if not user_ton_tai:
        return False, "Tên đăng nhập không tồn tại"
    
    user_info = users_db[username]
    
    # Kiểm tra password
    password_dung = user_info["password"] == password
    if not password_dung:
        return False, "Mật khẩu sai"
    
    # Kiểm tra tài khoản có hoạt động
    tai_khoan_hoat_dong = user_info["active"]
    if not tai_khoan_hoat_dong:
        return False, "Tài khoản đã bị khóa"
    
    return True, "Đăng nhập thành công"

def kiem_tra_quyen_admin(username):
    """Kiểm tra quyền admin"""
    if username not in users_db:
        return False
    
    return users_db[username]["role"] == "admin"

# Thử đăng nhập
max_attempts = 3
attempts = 0

while attempts < max_attempts:
    print(f"\n📝 Lần thử {attempts + 1}/{max_attempts}")
    
    username = input("👤 Username: ").strip()
    password = input("🔒 Password: ").strip()
    
    # Kiểm tra input rỗng
    if not username or not password:
        print("❌ Vui lòng nhập đầy đủ thông tin!")
        attempts += 1
        continue
    
    # Kiểm tra đăng nhập
    thanh_cong, thong_bao = kiem_tra_dang_nhap(username, password)
    
    if thanh_cong:
        print(f"✅ {thong_bao}")
        
        # Kiểm tra quyền
        la_admin = kiem_tra_quyen_admin(username)
        if la_admin:
            print("👑 Chào mừng Admin!")
            print("🛠️ Bạn có quyền quản trị hệ thống")
        else:
            print("👤 Chào mừng User!")
            print("📖 Bạn có quyền xem nội dung")
        break
    else:
        print(f"❌ {thong_bao}")
        attempts += 1
        
        # Cảnh báo nếu gần hết lượt
        if attempts < max_attempts:
            print(f"⚠️ Còn {max_attempts - attempts} lần thử")

else:
    print("\n🚫 ĐÃ HẾT LƯỢT THỬ!")
    print("🔒 Tài khoản bị khóa tạm thời")

Ví dụ 2: Hệ thống chấm điểm học sinh

python
# cham_diem_hoc_sinh.py
print("📊 HỆ THỐNG CHẤM ĐIỂM HỌC SINH")
print("=" * 40)

def nhap_diem(mon_hoc):
    """Nhập điểm một môn học"""
    while True:
        try:
            diem = float(input(f"📝 Điểm {mon_hoc} (0-10): "))
            
            # Kiểm tra điểm hợp lệ
            diem_hop_le = 0 <= diem <= 10
            if not diem_hop_le:
                print("❌ Điểm phải từ 0 đến 10!")
                continue
                
            return diem
        except ValueError:
            print("❌ Vui lòng nhập số!")

def phan_loai_hoc_luc(diem_tb):
    """Phân loại học lực theo điểm trung bình"""
    if diem_tb >= 9.0:
        return "Xuất sắc", "🏆"
    elif diem_tb >= 8.0:
        return "Giỏi", "🥇"
    elif diem_tb >= 6.5:
        return "Khá", "⭐"
    elif diem_tb >= 5.0:
        return "Trung bình", "👍"
    elif diem_tb >= 3.5:
        return "Yếu", "📚"
    else:
        return "Kém", "😰"

def phan_loai_hanh_kiem(diem_hanh_kiem):
    """Phân loại hạnh kiểm"""
    if diem_hanh_kiem >= 9.0:
        return "Tốt", "😊"
    elif diem_hanh_kiem >= 7.0:
        return "Khá", "🙂"
    elif diem_hanh_kiem >= 5.0:
        return "Trung bình", "😐"
    else:
        return "Yếu", "😞"

def kiem_tra_dieu_kien_len_lop(diem_tb, diem_hanh_kiem, co_mon_duoi_5):
    """Kiểm tra điều kiện lên lớp"""
    # Điều kiện học lực
    hoc_luc_dat = diem_tb >= 5.0
    
    # Điều kiện hạnh kiểm
    hanh_kiem_dat = diem_hanh_kiem >= 5.0
    
    # Không có môn nào dưới 5
    khong_co_mon_kem = not co_mon_duoi_5
    
    # Tất cả điều kiện phải thỏa mãn
    duoc_len_lop = hoc_luc_dat and hanh_kiem_dat and khong_co_mon_kem
    
    return duoc_len_lop, {
        'hoc_luc_dat': hoc_luc_dat,
        'hanh_kiem_dat': hanh_kiem_dat,
        'khong_co_mon_kem': khong_co_mon_kem
    }

# Nhập thông tin học sinh
ten_hs = input("👤 Tên học sinh: ").strip()
lop = input("🎓 Lớp: ").strip()

print(f"\n📝 NHẬP ĐIỂM CHO {ten_hs.upper()}")
print("-" * 30)

# Nhập điểm các môn
mon_hoc = ["Toán", "Văn", "Anh", "Lý", "Hóa", "Sinh", "Sử", "Địa"]
diem_cac_mon = {}

for mon in mon_hoc:
    diem = nhap_diem(mon)
    diem_cac_mon[mon] = diem

# Nhập điểm hạnh kiểm
diem_hanh_kiem = nhap_diem("Hạnh kiểm")

# Tính toán
diem_tb = sum(diem_cac_mon.values()) / len(diem_cac_mon)
co_mon_duoi_5 = any(diem < 5.0 for diem in diem_cac_mon.values())

# Phân loại
hoc_luc, emoji_hl = phan_loai_hoc_luc(diem_tb)
hanh_kiem, emoji_hk = phan_loai_hanh_kiem(diem_hanh_kiem)

# Kiểm tra lên lớp
duoc_len_lop, chi_tiet = kiem_tra_dieu_kien_len_lop(
    diem_tb, diem_hanh_kiem, co_mon_duoi_5
)

# Hiển thị kết quả
print(f"\n📊 KẾT QUẢ HỌC TẬP - {ten_hs.upper()}")
print("=" * 50)
print(f"🎓 Lớp: {lop}")
print(f"📈 Điểm TB: {diem_tb:.2f}")
print(f"{emoji_hl} Học lực: {hoc_luc}")
print(f"{emoji_hk} Hạnh kiểm: {hanh_kiem}")

print(f"\n📋 CHI TIẾT ĐIỂM:")
print("-" * 25)
for mon, diem in diem_cac_mon.items():
    status = "✅" if diem >= 5.0 else "❌"
    print(f"{status} {mon}: {diem:.1f}")

print(f"\n🎯 ĐIỀU KIỆN LÊN LỚP:")
print("-" * 25)
print(f"{'✅' if chi_tiet['hoc_luc_dat'] else '❌'} Học lực đạt (≥5.0): {chi_tiet['hoc_luc_dat']}")
print(f"{'✅' if chi_tiet['hanh_kiem_dat'] else '❌'} Hạnh kiểm đạt (≥5.0): {chi_tiet['hanh_kiem_dat']}")
print(f"{'✅' if chi_tiet['khong_co_mon_kem'] else '❌'} Không có môn dưới 5: {chi_tiet['khong_co_mon_kem']}")

print(f"\n🎯 KẾT LUẬN:")
if duoc_len_lop:
    print("🎉 ĐƯỢC LÊN LỚP!")
    print("👏 Chúc mừng em đã hoàn thành chương trình học!")
else:
    print("😞 PHẢI LÀM LẠI")
    print("💪 Em cần cố gắng hơn trong năm học tới!")

Ví dụ 3: Game câu hỏi trắc nghiệm

python
# game_trac_nghiem.py
import random

print("🧠 GAME CÂU HỎI TRẮC NGHIỆM")
print("=" * 35)

# Ngân hàng câu hỏi
cau_hoi_db = [
    {
        "cau_hoi": "Python được tạo ra bởi ai?",
        "dap_an": ["Guido van Rossum", "James Gosling", "Bjarne Stroustrup", "Dennis Ritchie"],
        "dung": 0
    },
    {
        "cau_hoi": "Kiểu dữ liệu nào sau đây là immutable trong Python?",
        "dap_an": ["list", "dict", "set", "tuple"],
        "dung": 3
    },
    {
        "cau_hoi": "Kết quả của 3 + 2 * 4 trong Python là?",
        "dap_an": ["20", "11", "14", "10"],
        "dung": 1
    },
    {
        "cau_hoi": "Cách nào sau đây để tạo comment trong Python?",
        "dap_an": ["// comment", "/* comment */", "# comment", "<!-- comment -->"],
        "dung": 2
    },
    {
        "cau_hoi": "bool(0) trong Python trả về giá trị gì?",
        "dap_an": ["True", "False", "None", "Error"],
        "dung": 1
    }
]

def hien_thi_cau_hoi(cau_hoi, so_thu_tu):
    """Hiển thị câu hỏi và các đáp án"""
    print(f"\n❓ Câu {so_thu_tu}: {cau_hoi['cau_hoi']}")
    print("-" * 40)
    
    for i, dap_an in enumerate(cau_hoi['dap_an']):
        print(f"  {chr(65 + i)}. {dap_an}")

def kiem_tra_dap_an(lua_chon, dap_an_dung):
    """Kiểm tra đáp án có đúng không"""
    if not lua_chon:
        return False
    
    # Chuyển đổi A,B,C,D thành 0,1,2,3
    if lua_chon.upper() in ['A', 'B', 'C', 'D']:
        chi_so = ord(lua_chon.upper()) - ord('A')
        return chi_so == dap_an_dung
    
    return False

def tinh_diem(so_cau_dung, tong_so_cau):
    """Tính điểm và phân loại"""
    ty_le = (so_cau_dung / tong_so_cau) * 100
    
    if ty_le >= 90:
        return ty_le, "Xuất sắc", "🏆"
    elif ty_le >= 80:
        return ty_le, "Giỏi", "🥇"
    elif ty_le >= 70:
        return ty_le, "Khá", "⭐"
    elif ty_le >= 60:
        return ty_le, "Trung bình", "👍"
    else:
        return ty_le, "Cần cố gắng", "📚"

# Thiết lập game
ten_nguoi_choi = input("👤 Nhập tên của bạn: ").strip()
if not ten_nguoi_choi:
    ten_nguoi_choi = "Người chơi"

# Lựa chọn độ khó
print(f"\n🎯 Chào {ten_nguoi_choi}! Chọn độ khó:")
print("1. Dễ (3 câu)")
print("2. Trung bình (5 câu)")
print("3. Khó (tất cả câu)")

while True:
    do_kho = input("Chọn (1-3): ").strip()
    if do_kho in ['1', '2', '3']:
        break
    print("❌ Vui lòng chọn 1, 2 hoặc 3!")

# Xác định số câu hỏi
so_cau_map = {'1': 3, '2': 5, '3': len(cau_hoi_db)}
so_cau_hoi = so_cau_map[do_kho]

# Chọn câu hỏi ngẫu nhiên
cau_hoi_chon = random.sample(cau_hoi_db, so_cau_hoi)

print(f"\n🚀 Bắt đầu game với {so_cau_hoi} câu hỏi!")
print("💡 Nhập A, B, C hoặc D để trả lời")

# Bắt đầu game
so_cau_dung = 0
danh_sach_ket_qua = []

for i, cau_hoi in enumerate(cau_hoi_chon, 1):
    hien_thi_cau_hoi(cau_hoi, i)
    
    # Nhận đáp án từ người chơi
    while True:
        lua_chon = input(f"\n👉 Đáp án của bạn: ").strip()
        
        # Kiểm tra input hợp lệ
        input_hop_le = lua_chon.upper() in ['A', 'B', 'C', 'D']
        if input_hop_le:
            break
        print("❌ Vui lòng nhập A, B, C hoặc D!")
    
    # Kiểm tra đáp án
    dap_an_dung = kiem_tra_dap_an(lua_chon, cau_hoi['dung'])
    
    if dap_an_dung:
        print("✅ Chính xác!")
        so_cau_dung += 1
        danh_sach_ket_qua.append(True)
    else:
        dap_an_dung_chu = chr(65 + cau_hoi['dung'])
        print(f"❌ Sai! Đáp án đúng là {dap_an_dung_chu}")
        danh_sach_ket_qua.append(False)
    
    # Hiển thị tiến độ
    if i < so_cau_hoi:
        input("\n⏯️ Nhấn Enter để tiếp tục...")

# Tính kết quả cuối
ty_le, xep_loai, emoji = tinh_diem(so_cau_dung, so_cau_hoi)

# Hiển thị kết quả
print(f"\n🎊 KẾT QUẢ CUỐI CÙNG - {ten_nguoi_choi.upper()}")
print("=" * 50)
print(f"✅ Số câu đúng: {so_cau_dung}/{so_cau_hoi}")
print(f"📊 Tỷ lệ: {ty_le:.1f}%")
print(f"{emoji} Xếp loại: {xep_loai}")

# Chi tiết từng câu
print(f"\n📋 CHI TIẾT:")
print("-" * 20)
for i, (ket_qua, cau_hoi) in enumerate(zip(danh_sach_ket_qua, cau_hoi_chon), 1):
    status = "✅" if ket_qua else "❌"
    print(f"{status} Câu {i}: {cau_hoi['cau_hoi'][:30]}...")

# Khuyến nghị
print(f"\n💬 NHẬN XÉT:")
if ty_le >= 80:
    print("🎉 Xuất sắc! Bạn có kiến thức Python rất tốt!")
elif ty_le >= 60:
    print("👍 Khá tốt! Hãy tiếp tục học tập để cải thiện!")
else:
    print("📚 Cần ôn tập thêm! Đừng nản chí, cố gắng lên!")

print("🔄 Chơi lại để cải thiện điểm số!")

🏋️ Thực hành

Bài tập 1: Validator dữ liệu nâng cao

Nhiệm vụ: Tạo hệ thống validate form đăng ký

python
# TODO: Validate form với các điều kiện:
# - Username: 3-20 ký tự, chỉ chữ và số
# - Password: 8+ ký tự, có chữ hoa, thường, số, ký tự đặc biệt
# - Email: format đúng
# - Age: 13-120
# - Terms: phải đồng ý

Đáp án:

python
# validator_form.py
import re

def validate_username(username):
    """Validate username"""
    if not username:
        return False, "Username không được rỗng"
    
    length_ok = 3 <= len(username) <= 20
    if not length_ok:
        return False, "Username phải từ 3-20 ký tự"
    
    format_ok = username.isalnum()
    if not format_ok:
        return False, "Username chỉ chứa chữ và số"
    
    return True, "Username hợp lệ"

def validate_password(password):
    """Validate password strength"""
    if len(password) < 8:
        return False, "Password phải có ít nhất 8 ký tự"
    
    has_upper = any(c.isupper() for c in password)
    has_lower = any(c.islower() for c in password)
    has_digit = any(c.isdigit() for c in password)
    has_special = any(c in "!@#$%^&*()_+-=" for c in password)
    
    all_conditions = has_upper and has_lower and has_digit and has_special
    
    if not all_conditions:
        missing = []
        if not has_upper: missing.append("chữ hoa")
        if not has_lower: missing.append("chữ thường") 
        if not has_digit: missing.append("số")
        if not has_special: missing.append("ký tự đặc biệt")
        
        return False, f"Password cần: {', '.join(missing)}"
    
    return True, "Password mạnh"

def validate_email(email):
    """Validate email format"""
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    if re.match(pattern, email):
        return True, "Email hợp lệ"
    else:
        return False, "Email không đúng định dạng"

def validate_age(age):
    """Validate age range"""
    try:
        age_num = int(age)
        if 13 <= age_num <= 120:
            return True, "Tuổi hợp lệ"
        else:
            return False, "Tuổi phải từ 13-120"
    except ValueError:
        return False, "Tuổi phải là số"

print("📝 FORM ĐĂNG KÝ TÀI KHOẢN")
print("=" * 30)

# Collect data
data = {}
data['username'] = input("👤 Username: ")
data['password'] = input("🔒 Password: ")
data['email'] = input("📧 Email: ")
data['age'] = input("🎂 Tuổi: ")

terms_input = input("📋 Đồng ý điều khoản? (y/n): ").lower()
data['terms_agreed'] = terms_input in ['y', 'yes', 'có']

# Validate
print("\n🔍 KẾT QUẢ KIỂM TRA:")
print("-" * 25)

all_valid = True
validations = [
    ('Username', validate_username, data['username']),
    ('Password', validate_password, data['password']),
    ('Email', validate_email, data['email']),
    ('Tuổi', validate_age, data['age'])
]

for field_name, validator, value in validations:
    valid, message = validator(value)
    status = "✅" if valid else "❌"
    print(f"{status} {field_name}: {message}")
    if not valid:
        all_valid = False

# Check terms
if data['terms_agreed']:
    print("✅ Điều khoản: Đã đồng ý")
else:
    print("❌ Điều khoản: Chưa đồng ý")
    all_valid = False

print(f"\n🎯 KẾT LUẬN:")
if all_valid:
    print("🎉 Đăng ký thành công!")
else:
    print("❌ Vui lòng sửa các lỗi trên!")

Bài tập 2: Logic puzzle solver

Nhiệm vụ: Giải bài toán logic

python
# TODO: Giải bài toán:
# - Có 3 người: An, Bình, Cường
# - Mỗi người có nghề: giáo viên, bác sĩ, kỹ sư
# - Điều kiện logic để tìm nghề của từng người

Đáp án:

python
# logic_puzzle.py
def giai_bai_toan_logic():
    """
    Bài toán: 3 người An, Bình, Cường có nghề giáo viên, bác sĩ, kỹ sư
    Điều kiện:
    1. An không phải bác sĩ
    2. Bình không phải kỹ sư  
    3. Nếu An là giáo viên thì Cường là bác sĩ
    4. Nếu Bình là giáo viên thì An là kỹ sư
    """
    
    nguoi = ["An", "Binh", "Cuong"]
    nghe = ["Giao_vien", "Bac_si", "Ky_su"]
    
    # Thử tất cả các khả năng
    for an_nghe in nghe:
        for binh_nghe in nghe:
            for cuong_nghe in nghe:
                # Mỗi người một nghề khác nhau
                if len(set([an_nghe, binh_nghe, cuong_nghe])) != 3:
                    continue
                
                # Điều kiện 1: An không phải bác sĩ
                if an_nghe == "Bac_si":
                    continue
                
                # Điều kiện 2: Bình không phải kỹ sư
                if binh_nghe == "Ky_su":
                    continue
                
                # Điều kiện 3: Nếu An là giáo viên thì Cường là bác sĩ
                if an_nghe == "Giao_vien" and cuong_nghe != "Bac_si":
                    continue
                
                # Điều kiện 4: Nếu Bình là giáo viên thì An là kỹ sư
                if binh_nghe == "Giao_vien" and an_nghe != "Ky_su":
                    continue
                
                # Tìm thấy đáp án
                return {
                    "An": an_nghe,
                    "Binh": binh_nghe, 
                    "Cuong": cuong_nghe
                }
    
    return None

print("🧩 GIẢI BÀI TOÁN LOGIC")
print("=" * 25)

print("📋 Bài toán:")
print("- 3 người: An, Bình, Cường")
print("- 3 nghề: Giáo viên, Bác sĩ, Kỹ sư")
print("- Điều kiện:")
print("  1. An không phải bác sĩ")
print("  2. Bình không phải kỹ sư")
print("  3. Nếu An là giáo viên thì Cường là bác sĩ")
print("  4. Nếu Bình là giáo viên thì An là kỹ sư")

dap_an = giai_bai_toan_logic()

if dap_an:
    print(f"\n✅ ĐÁP ÁN:")
    for nguoi, nghe in dap_an.items():
        nghe_viet = nghe.replace("_", " ").lower()
        print(f"  {nguoi}: {nghe_viet}")
else:
    print("\n❌ Không tìm thấy đáp án!")

Bài tập 3: Boolean expression evaluator

Nhiệm vụ: Tạo máy tính biểu thức boolean

python
# TODO: Tính giá trị biểu thức logic:
# - Nhập biểu thức như "A and B or not C"
# - Nhập giá trị cho các biến
# - Tính kết quả

Đáp án:

python
# boolean_calculator.py
import re

def parse_variables(expression):
    """Tìm tất cả biến trong biểu thức"""
    # Tìm các chữ cái đơn không phải từ khóa
    pattern = r'\b[A-Z]\b'
    variables = set(re.findall(pattern, expression))
    return sorted(variables)

def evaluate_expression(expression, values):
    """Đánh giá biểu thức boolean"""
    # Thay thế biến bằng giá trị
    expr = expression
    for var, value in values.items():
        expr = re.sub(rf'\b{var}\b', str(value), expr)
    
    # Thay thế từ khóa logic
    expr = expr.replace('and', ' and ')
    expr = expr.replace('or', ' or ')
    expr = expr.replace('not', ' not ')
    
    try:
        # Đánh giá biểu thức
        result = eval(expr)
        return result, None
    except Exception as e:
        return None, str(e)

print("🧮 BOOLEAN EXPRESSION CALCULATOR")
print("=" * 40)

print("📝 Hướng dẫn:")
print("- Sử dụng biến A, B, C, D...")
print("- Toán tử: and, or, not")
print("- Ví dụ: A and B or not C")

while True:
    print("\n" + "="*30)
    expression = input("🔢 Nhập biểu thức: ").strip()
    
    if not expression:
        break
    
    # Tìm biến
    variables = parse_variables(expression)
    
    if not variables:
        print("❌ Không tìm thấy biến nào!")
        continue
    
    print(f"\n📋 Biến tìm thấy: {', '.join(variables)}")
    
    # Nhập giá trị cho biến
    values = {}
    for var in variables:
        while True:
            value_input = input(f"  {var} = (True/False): ").strip().lower()
            if value_input in ['true', 't', '1', 'yes']:
                values[var] = True
                break
            elif value_input in ['false', 'f', '0', 'no']:
                values[var] = False
                break
            else:
                print("    ❌ Nhập True hoặc False!")
    
    # Đánh giá biểu thức
    result, error = evaluate_expression(expression, values)
    
    print(f"\n🎯 KẾT QUẢ:")
    print(f"Biểu thức: {expression}")
    for var, val in values.items():
        print(f"{var} = {val}")
    
    if error:
        print(f"❌ Lỗi: {error}")
    else:
        print(f"➡️ Kết quả: {result}")
    
    # Bảng chân trị
    show_table = input("\n📊 Hiển thị bảng chân trị? (y/n): ").lower()
    if show_table in ['y', 'yes']:
        print(f"\n📊 BẢNG CHÂN TRỊ:")
        
        # Header
        header = " | ".join(variables) + " | Kết quả"
        print(header)
        print("-" * len(header))
        
        # Tất cả combinations
        from itertools import product
        
        for combo in product([False, True], repeat=len(variables)):
            combo_values = dict(zip(variables, combo))
            result, _ = evaluate_expression(expression, combo_values)
            
            row = " | ".join(f"{str(val):^5}" for val in combo)
            row += f" | {str(result):^7}"
            print(row)

print("\n👋 Tạm biệt!")

📋 Tóm tắt

Giá trị boolean:

Giá trịMô tảVí dụ
TrueĐúngis_student = True
FalseSaiis_finished = False

Toán tử logic:

python
# AND - tất cả phải đúng
True and True    # True
True and False   # False

# OR - ít nhất một đúng
True or False    # True
False or False   # False

# NOT - đảo ngược
not True         # False
not False        # True

Toán tử so sánh:

python
# So sánh bằng/khác
5 == 5          # True
5 != 3          # True

# So sánh lớn nhỏ
10 > 5          # True
3 <= 3          # True

# Membership
'a' in 'abc'    # True
5 not in [1,2,3] # True

Truthy/Falsy values:

python
# Falsy (được coi là False)
bool(0)         # False
bool("")        # False  
bool([])        # False
bool(None)      # False

# Truthy (được coi là True)
bool(1)         # True
bool("hello")   # True
bool([1])       # True

Patterns thường dùng:

python
# Kiểm tra điều kiện kết hợp
if age >= 18 and has_license:
    print("Có thể lái xe")

# Short-circuit evaluation
result = expensive_function() or default_value

# Validation
if username and password and email:
    # Tiếp tục xử lý

# Boolean flag
is_valid = True
if not condition1:
    is_valid = False
if not condition2:
    is_valid = False

Best practices:

  1. 🎯 Explicit comparison: if x is True: thay vì if x == True:
  2. 🔍 Use truthiness: if my_list: thay vì if len(my_list) > 0:
  3. 📝 Clear variable names: is_valid, has_permission, can_access
  4. ⚡ Short-circuit: Đặt điều kiện nhanh trước trong and
  5. 🚫 Avoid double negative: if not disabled: thay vì if not not_enabled:

Chuẩn bị cho bài tiếp theo:

Bài tiếp theo sẽ học về 🔀 Ép kiểu dữ liệu - cách chuyển đổi giữa các kiểu dữ liệu trong Python!


💡 Mẹo: Boolean là nền tảng của logic lập trình. Hiểu rõ và sử dụng thành thạo sẽ giúp code rõ ràng và hiệu quả!

✅ Thực hành: Thử viết các điều kiện phức tạp và sử dụng bảng chân trị để kiểm tra logic!

🐍 Khóa học Python căn bản bằng tiếng Việt