Bài 9: Control Flow - If/Else

Mục Tiêu Bài Học

Sau khi hoàn thành bài này, bạn sẽ:

  • ✅ Hiểu conditional statements và control flow
  • ✅ Sử dụng if, elif, else
  • ✅ Kết hợp logical operators (and, or, not)
  • ✅ Làm việc với nested conditions
  • ✅ Áp dụng ternary operator và best practices

If Statement Cơ Bản

If statement cho phép code chạy có điều kiện.

# Cú pháp# if condition:#     code block age = 18 if age >= 18:    print("You are an adult") # Output: You are an adult

Indentation (Thụt đầu dòng) quan trọng:

age = 20 # ✅ Đúngif age >= 18:    print("Line 1")    print("Line 2")    print("Line 3") # ❌ Sai - IndentationError# if age >= 18:# print("No indent") # ❌ Sai - Mixed indentation# if age >= 18:#     print("4 spaces")#   print("2 spaces")  # Error!

Boolean Conditions:

# Comparison operatorsx = 10if x > 5:    print("x is greater than 5") if x == 10:    print("x equals 10") if x != 20:    print("x is not 20") # Boolean valuesis_active = Trueif is_active:    print("User is active") # Expression returning booleannumbers = [1, 2, 3]if len(numbers) > 0:    print("List is not empty")

If-Else Statement

Else chạy khi condition là False.

age = 15 if age >= 18:    print("You are an adult")else:    print("You are a minor") # Output: You are a minor

Ví dụ thực tế:

# Login checkusername = "alice"password = "secret123" if username == "alice" and password == "secret123":    print("Login successful!")else:    print("Invalid credentials!") # Even or oddnumber = 7if number % 2 == 0:    print(f"{number} is even")else:    print(f"{number} is odd") # Pass or failscore = 75if score >= 80:    print("Pass")else:    print("Fail")

If-Elif-Else Chain

Elif (else if) cho phép check nhiều conditions.

score = 85 if score >= 90:    print("Grade: A")elif score >= 80:    print("Grade: B")elif score >= 70:    print("Grade: C")elif score >= 60:    print("Grade: D")else:    print("Grade: F") # Output: Grade: B

Flow:

  • Check if first
  • Nếu False → check elif đầu tiên
  • Nếu False → check elif tiếp theo
  • Nếu tất cả False → chạy else
  • Chỉ một block được chạy!
# Chỉ block đầu tiên đúng được chạyx = 15 if x > 10:    print("Greater than 10")  # ✅ Chạyelif x > 5:    print("Greater than 5")   # ❌ Không chạy (dù đúng)elif x > 0:    print("Greater than 0")   # ❌ Không chạy

Ví dụ thực tế:

# Ticket priceage = 25 if age < 3:    price = 0    category = "Free"elif age < 12:    price = 10    category = "Child"elif age < 60:    price = 20    category = "Adult"else:    price = 15    category = "Senior" print(f"Category: {category}")print(f"Price: ${price}") # BMI classificationbmi = 24.5 if bmi < 18.5:    status = "Underweight"elif bmi < 25:    status = "Normal"elif bmi < 30:    status = "Overweight"else:    status = "Obese" print(f"BMI: {bmi} - Status: {status}")

Logical Operators

and - Tất cả phải True

# and - cả hai phải Trueage = 25has_license = True if age >= 18 and has_license:    print("Can drive") # Multiple conditionsscore = 85attendance = 90 if score >= 80 and attendance >= 85:    print("Excellent performance") # All conditionsusername = "alice"password = "secret"is_verified = True if username == "alice" and password == "secret" and is_verified:    print("Access granted")

or - Ít nhất một True

# or - ít nhất một Trueis_weekend = Trueis_holiday = False if is_weekend or is_holiday:    print("No work today!") # Multiple conditionspayment_method = "credit_card" if payment_method == "cash" or payment_method == "credit_card" or payment_method == "bank":    print("Payment accepted") # Membership check (tốt hơn)valid_methods = ["cash", "credit_card", "bank"]if payment_method in valid_methods:    print("Payment accepted")

not - Đảo ngược

# not - đảo ngược booleanis_raining = False if not is_raining:    print("Let's go outside") # Check emptydata = []if not data:    print("List is empty") # Check Nonevalue = Noneif value is not None:    print("Value exists") # Combine with othersage = 16has_permission = False if age >= 18 or (age >= 16 and has_permission):    print("Can enter")

Kết Hợp Logical Operators

# Precedence: not > and > or# Dùng () để rõ ràng age = 25is_student = Falsehas_coupon = True # Complex conditionif (age < 18 or is_student) and has_coupon:    print("Discount applied") # Validate user inputusername = "alice"password = "secret123"length_ok = len(password) >= 8has_number = any(c.isdigit() for c in password) if username and password and length_ok and has_number:    print("Registration successful")else:    print("Invalid input")

Short-circuit Evaluation

# and - stops at first Falsedef check1():    print("Check 1")    return False def check2():    print("Check 2")    return True if check1() and check2():  # check2() không chạy    print("Both True")# Output: Check 1 # or - stops at first Truedef check3():    print("Check 3")    return True def check4():    print("Check 4")    return False if check3() or check4():  # check4() không chạy    print("At least one True")# Output: Check 3 # Ứng dụng: avoid errorsuser = Noneif user and user.get("name"):  # Không lỗi khi user = None    print(user["name"])

Nested If Statements

Nested if là if bên trong if.

# Nested ifage = 25has_license = Truehas_car = True if age >= 18:    if has_license:        if has_car:            print("Can drive own car")        else:            print("Can drive rental car")    else:        print("Need to get license")else:    print("Too young to drive")

Flatten với logical operators:

# Thay vì nestedif age >= 18:    if has_license:        if has_car:            print("Can drive") # Dùng andif age >= 18 and has_license and has_car:    print("Can drive")

Ví dụ thực tế:

# User authenticationusername = "alice"password = "secret"is_active = Trueis_verified = True if username == "alice" and password == "secret":    if is_active:        if is_verified:            print("Login successful")        else:            print("Please verify your email")    else:        print("Account is deactivated")else:    print("Invalid credentials") # Game logichealth = 80has_weapon = Trueenemy_nearby = True if health > 0:    if enemy_nearby:        if has_weapon:            print("Attack enemy")        else:            print("Run away")    else:        print("Explore area")else:    print("Game Over")

Ternary Operator (Conditional Expression)

Ternary operator là if-else trong một dòng.

# Cú pháp: value_if_true if condition else value_if_false age = 20 # Normal if-elseif age >= 18:    status = "Adult"else:    status = "Minor" # Ternary operatorstatus = "Adult" if age >= 18 else "Minor" print(status)  # Adult

Ví dụ:

# Even or oddnumber = 7result = "Even" if number % 2 == 0 else "Odd"print(result)  # Odd # Max of two numbersa, b = 10, 20max_value = a if a > b else bprint(max_value)  # 20 # Discountprice = 100is_member = Truefinal_price = price * 0.9 if is_member else priceprint(f"Price: ${final_price}") # Gradescore = 85grade = "Pass" if score >= 80 else "Fail"print(grade) # Format stringcount = 1message = f"{count} item" if count == 1 else f"{count} items"print(message)  # 1 item

Nested Ternary (không khuyến nghị):

# ❌ Khó đọcscore = 85grade = "A" if score >= 90 else "B" if score >= 80 else "C" # ✅ Dùng if-elif-else thayif score >= 90:    grade = "A"elif score >= 80:    grade = "B"else:    grade = "C"

Truthy và Falsy Values

Python coi một số values là False.

# Falsy values# - False# - None# - 0, 0.0# - "" (empty string)# - [] (empty list)# - {} (empty dict)# - () (empty tuple)# - set() (empty set) # Check empty listdata = []if data:    print("Has data")else:    print("Empty")  # ✅ Output # Check stringname = ""if name:    print(f"Hello, {name}")else:    print("Name is empty")  # ✅ Output # Check Nonevalue = Noneif value:    print("Value exists")else:    print("Value is None")  # ✅ Output # Explicit checks (better)data = []if len(data) > 0:  # More explicit    print("Has data") if value is not None:  # Better than 'if value'    print("Value exists")

Match-Case Statement (Python 3.10+)

Match-case giống switch-case trong ngôn ngữ khác.

# Match-case (Python 3.10+)status_code = 404 match status_code:    case 200:        message = "OK"    case 404:        message = "Not Found"    case 500:        message = "Server Error"    case _:  # default        message = "Unknown" print(message)  # Not Found # With patternspoint = (0, 1) match point:    case (0, 0):        print("Origin")    case (0, y):        print(f"Y-axis at {y}")    case (x, 0):        print(f"X-axis at {x}")    case (x, y):        print(f"Point at ({x}, {y})") # With conditionsage = 25 match age:    case n if n < 18:        print("Minor")    case n if 18 <= n < 60:        print("Adult")    case n if n >= 60:        print("Senior")

Ví Dụ Thực Tế

1. Simple Calculator

num1 = float(input("Enter first number: "))operator = input("Enter operator (+, -, *, /): ")num2 = float(input("Enter second number: ")) if operator == "+":    result = num1 + num2elif operator == "-":    result = num1 - num2elif operator == "*":    result = num1 * num2elif operator == "/":    if num2 != 0:        result = num1 / num2    else:        result = "Error: Division by zero"else:    result = "Error: Invalid operator" print(f"Result: {result}")

2. Login System

# User database (simplified)users = {    "alice": {"password": "secret123", "role": "admin"},    "bob": {"password": "pass456", "role": "user"}} username = input("Username: ")password = input("Password: ") if username in users:    if users[username]["password"] == password:        role = users[username]["role"]        print(f"Login successful! Welcome, {username}")        print(f"Role: {role}")                if role == "admin":            print("You have admin privileges")    else:        print("Incorrect password")else:    print("User not found")

3. Grade Calculator

# Input scoresmath = float(input("Math score: "))physics = float(input("Physics score: "))chemistry = float(input("Chemistry score: ")) # Validate scoresif not (0 <= math <= 100 and 0 <= physics <= 100 and 0 <= chemistry <= 100):    print("Error: Scores must be between 0 and 100")else:    # Calculate average    average = (math + physics + chemistry) / 3        # Determine grade    if average >= 90:        grade = "A"        status = "Excellent"    elif average >= 80:        grade = "B"        status = "Good"    elif average >= 70:        grade = "C"        status = "Average"    elif average >= 60:        grade = "D"        status = "Below Average"    else:        grade = "F"        status = "Fail"        # Display results    print(f"\nAverage: {average:.2f}")    print(f"Grade: {grade}")    print(f"Status: {status}")        # Check if passed    if grade != "F" and math >= 50 and physics >= 50 and chemistry >= 50:        print("Result: PASSED")    else:        print("Result: FAILED")

4. Shopping Discount System

# Shopping carttotal = float(input("Total amount: $"))is_member = input("Are you a member? (yes/no): ").lower() == "yes"has_coupon = input("Do you have a coupon? (yes/no): ").lower() == "yes" discount = 0 # Member discountif is_member:    discount += 0.10  # 10% member discount    print("Member discount: 10%") # Coupon discountif has_coupon:    discount += 0.05  # 5% coupon discount    print("Coupon discount: 5%") # Volume discountif total >= 500:    discount += 0.15  # 15% volume discount    print("Volume discount (>=$500): 15%")elif total >= 200:    discount += 0.10  # 10% volume discount    print("Volume discount (>=$200): 10%")elif total >= 100:    discount += 0.05  # 5% volume discount    print("Volume discount (>=$100): 5%") # Calculate final pricediscount_amount = total * discountfinal_price = total - discount_amount print(f"\nTotal: ${total:.2f}")print(f"Total discount: {discount * 100:.0f}%")print(f"Discount amount: ${discount_amount:.2f}")print(f"Final price: ${final_price:.2f}")

5. Age Category Classifier

age = int(input("Enter age: ")) # Validate ageif age < 0:    print("Invalid age")elif age <= 2:    category = "Infant"    description = "Needs constant care"elif age <= 12:    category = "Child"    description = "School age"elif age <= 17:    category = "Teenager"    description = "High school age"elif age <= 64:    category = "Adult"    description = "Working age"else:    category = "Senior"    description = "Retirement age" if age >= 0:    print(f"Category: {category}")    print(f"Description: {description}")        # Additional info    if age >= 18:        print("✓ Can vote")        print("✓ Can drive")        if age >= 21:        print("✓ Can drink alcohol (in some countries)")

Best Practices

# 1. Dùng comparison operators rõ ràng# ❌ Không tốtif len(items) > 0:    pass # ✅ Tốt hơnif items:    pass # 2. Avoid complex nested conditions# ❌ Khó đọcif condition1:    if condition2:        if condition3:            do_something() # ✅ Dễ đọcif condition1 and condition2 and condition3:    do_something() # 3. Early return (guard clause)# ❌ Nesteddef process(data):    if data:        if len(data) > 0:            if data[0] is not None:                return data[0]    return None # ✅ Early returndef process(data):    if not data:        return None    if len(data) == 0:        return None    if data[0] is None:        return None    return data[0] # 4. Use is for None checks# ❌ Không tốtif value == None:    pass # ✅ Tốtif value is None:    pass

Bài Tập Thực Hành

Bài 1: Leap Year

Viết chương trình check năm nhuận:

  • Chia hết cho 4
  • Không chia hết cho 100, trừ khi chia hết cho 400

Bài 2: Triangle Validator

Kiểm tra 3 cạnh có tạo thành tam giác hợp lệ không:

  • Tổng 2 cạnh > cạnh còn lại
  • Classify: equilateral, isosceles, scalene

Bài 3: Password Strength

Check password strength:

  • Weak: < 8 chars
  • Medium: >= 8 chars, has letters and numbers
  • Strong: >= 8 chars, has letters, numbers, and symbols

Bài 4: Temperature Converter

Convert và classify temperature:

  • Input: temp và unit (C/F)
  • Convert to other unit
  • Classify: freezing, cold, mild, warm, hot

Bài 5: ATM System

Simulate ATM:

  • Check balance
  • Withdraw (check sufficient funds)
  • Deposit
  • Input validation

Tóm Tắt

if condition: - Basic conditional
if-else - Two branches
if-elif-else - Multiple conditions
✅ Logical operators: and, or, not
✅ Ternary: value_if_true if condition else value_if_false
✅ Truthy/Falsy values
✅ Match-case (Python 3.10+)

Bài Tiếp Theo

Bài 10: Loops - For và while loops, loop control (break, continue), nested loops.


Remember:

  • Indentation là bắt buộc trong Python
  • Chỉ một block trong if-elif-else được chạy
  • andor có short-circuit evaluation
  • Dùng is cho None checks
  • Keep conditions simple và readable
  • Early return giúp code sạch hơn!