Python Control Flow: If, Loops và Logic

Tìm hiểu về control flow trong Python: if/else, for loops, while loops và các cấu trúc điều khiển.

Control Flow là gì?

Control Flow (luồng điều khiển) quyết định thứ tự các câu lệnh được thực thi trong chương trình. Python cung cấp các cấu trúc điều khiển mạnh mẽ.

If / Elif / Else

# Cú pháp cơ bản
age = 18

if age < 13:
    print("Trẻ em")
elif age < 20:
    print("Thiếu niên")
else:
    print("Người lớn")

# Output: Thiếu niên

Comparison Operators

x = 10
y = 20

print(x == y)   # False - bằng nhau
print(x != y)   # True  - khác nhau
print(x < y)    # True  - nhỏ hơn
print(x > y)    # False - lớn hơn
print(x <= y)   # True  - nhỏ hơn hoặc bằng
print(x >= y)   # False - lớn hơn hoặc bằng

Logical Operators

a = True
b = False

print(a and b)  # False - VÀ
print(a or b)   # True  - HOẶC
print(not a)    # False - PHỦ ĐỊNH

# Ví dụ thực tế
port = 443
is_secure = True

if port == 443 and is_secure:
    print("HTTPS connection")

Nested Conditions

user_role = "admin"
is_authenticated = True

if is_authenticated:
    if user_role == "admin":
        print("Full access granted")
    elif user_role == "user":
        print("Limited access granted")
    else:
        print("Guest access")
else:
    print("Please login first")

Ternary Operator

# Cú pháp: value_if_true if condition else value_if_false
age = 20
status = "adult" if age >= 18 else "minor"
print(status)  # adult

# Ứng dụng trong security
is_encrypted = True
protocol = "HTTPS" if is_encrypted else "HTTP"

For Loops

# Lặp qua list
ports = [22, 80, 443, 3306]
for port in ports:
    print(f"Scanning port {port}")

# Lặp với index
for i, port in enumerate(ports):
    print(f"{i+1}. Port {port}")

# range() function
for i in range(5):      # 0, 1, 2, 3, 4
    print(i)

for i in range(1, 6):   # 1, 2, 3, 4, 5
    print(i)

for i in range(0, 10, 2):  # 0, 2, 4, 6, 8
    print(i)

Lặp qua Dictionary

services = {
    22: "SSH",
    80: "HTTP",
    443: "HTTPS"
}

# Lặp qua keys
for port in services:
    print(port)

# Lặp qua values
for name in services.values():
    print(name)

# Lặp qua key-value pairs
for port, name in services.items():
    print(f"Port {port}: {name}")

While Loops

# Cú pháp cơ bản
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1

# Vòng lặp vô hạn với điều kiện thoát
while True:
    user_input = input("Enter 'quit' to exit: ")
    if user_input == "quit":
        break
    print(f"You entered: {user_input}")

Break và Continue

# break - thoát khỏi vòng lặp
for port in range(1, 100):
    if port == 22:
        print(f"Found SSH on port {port}")
        break

# continue - bỏ qua iteration hiện tại
for num in range(10):
    if num % 2 == 0:  # Bỏ qua số chẵn
        continue
    print(num)  # 1, 3, 5, 7, 9

# else với loop (chạy khi không bị break)
for port in [80, 443, 8080]:
    if port == 22:
        print("SSH found!")
        break
else:
    print("SSH not found in common ports")

List Comprehension

# Cách thông thường
squares = []
for x in range(10):
    squares.append(x ** 2)

# List comprehension
squares = [x ** 2 for x in range(10)]

# Với điều kiện
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]

# Nested comprehension
matrix = [[j for j in range(3)] for i in range(3)]
# [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

Match Statement (Python 3.10+)

def get_service_name(port: int) -> str:
    match port:
        case 22:
            return "SSH"
        case 80:
            return "HTTP"
        case 443:
            return "HTTPS"
        case 3306:
            return "MySQL"
        case _:  # default case
            return "Unknown"

print(get_service_name(443))  # HTTPS

Ứng dụng: Port Range Validator

def validate_port_range(start: int, end: int) -> bool:
    """Validate port range for scanning"""
    
    if not isinstance(start, int) or not isinstance(end, int):
        print("Error: Ports must be integers")
        return False
    
    if start < 1 or end > 65535:
        print("Error: Port range must be 1-65535")
        return False
    
    if start > end:
        print("Error: Start port must be <= end port")
        return False
    
    return True

# Test
if validate_port_range(1, 1024):
    print("Valid range - scanning...")

Bước tiếp theo

Trong bài tiếp theo, chúng ta sẽ học về:

  • Functions: Định nghĩa và sử dụng functions
  • Parameters và Arguments
  • Return values và Scope

💡 Pro tip: Tránh nested loops quá sâu (>3 levels). Nếu cần, hãy refactor thành functions.