Bài 10: Loops - Vòng Lặp
Mục Tiêu Bài Học
Sau khi hoàn thành bài này, bạn sẽ:
- ✅ Hiểu for và while loops
- ✅ Sử dụng range(), enumerate(), zip()
- ✅ Kiểm soát loops với break và continue
- ✅ Làm việc với nested loops
- ✅ Áp dụng loop patterns thực tế
For Loop
For loop dùng để iterate qua một sequence (list, tuple, string, etc.).
Cú Pháp Cơ Bản
# Syntax: for item in iterable:# code block # Loop qua listfruits = ["apple", "banana", "orange"]for fruit in fruits: print(fruit)# apple# banana# orange # Loop qua stringfor char in "Python": print(char)# P, y, t, h, o, n # Loop qua tuplecolors = ("red", "green", "blue")for color in colors: print(color)
range() Function
range() tạo sequence của numbers.
# range(stop) - từ 0 đến stop-1for i in range(5): print(i, end=" ")# 0 1 2 3 4 # range(start, stop) - từ start đến stop-1for i in range(2, 6): print(i, end=" ")# 2 3 4 5 # range(start, stop, step) - với bước nhảyfor i in range(0, 10, 2): print(i, end=" ")# 0 2 4 6 8 # Đếm ngượcfor i in range(10, 0, -1): print(i, end=" ")# 10 9 8 7 6 5 4 3 2 1 # Ứng dụng# Print multiplication tablen = 5for i in range(1, 11): print(f"{n} x {i} = {n * i}")
enumerate() - Loop với Index
enumerate() trả về cả index và value.
fruits = ["apple", "banana", "orange"] # Với enumeratefor index, fruit in enumerate(fruits): print(f"{index}: {fruit}")# 0: apple# 1: banana# 2: orange # Start index từ 1for index, fruit in enumerate(fruits, start=1): print(f"{index}. {fruit}")# 1. apple# 2. banana# 3. orange # Ứng dụng: tìm vị trínumbers = [10, 20, 30, 40, 50]for i, num in enumerate(numbers): if num == 30: print(f"Found 30 at index {i}")
zip() - Loop Nhiều Iterables
zip() kết hợp nhiều iterables.
names = ["Alice", "Bob", "Charlie"]ages = [25, 30, 35] # Zip 2 listsfor name, age in zip(names, ages): print(f"{name} is {age} years old")# Alice is 25 years old# Bob is 30 years old# Charlie is 35 years old # Zip 3 listscities = ["Hanoi", "HCMC", "Danang"]for name, age, city in zip(names, ages, cities): print(f"{name}, {age}, lives in {city}") # Zip với enumeratefor i, (name, age) in enumerate(zip(names, ages), 1): print(f"{i}. {name}: {age}") # ⚠️ Zip stops at shortestlist1 = [1, 2, 3, 4, 5]list2 = ["a", "b", "c"]for num, letter in zip(list1, list2): print(num, letter)# 1 a# 2 b# 3 c
Loop qua Dictionary
person = { "name": "Alice", "age": 25, "city": "Hanoi"} # Loop qua keys (default)for key in person: print(key)# name, age, city # Loop qua keys (explicit)for key in person.keys(): print(f"{key}: {person[key]}") # Loop qua valuesfor value in person.values(): print(value) # Loop qua items (key-value pairs) - recommendedfor key, value in person.items(): print(f"{key}: {value}")
While Loop
While loop chạy khi condition còn True.
Cú Pháp Cơ Bản
# Syntax: while condition:# code block # Đếm từ 1 đến 5count = 1while count <= 5: print(count) count += 1# 1, 2, 3, 4, 5 # Sum numberstotal = 0num = 1while num <= 10: total += num num += 1print(f"Sum: {total}") # 55 # User input loopwhile True: answer = input("Continue? (yes/no): ") if answer.lower() == "no": break print("Continuing...")
While với Condition
# Đợi đến khi đủ điều kiệnpassword = ""while password != "secret": password = input("Enter password: ") if password != "secret": print("Wrong password, try again")print("Access granted!") # Tìm số chia hếtn = 100while n % 7 != 0: n += 1print(f"First number >= 100 divisible by 7: {n}") # Fibonaccia, b = 0, 1while a < 100: print(a, end=" ") a, b = b, a + b# 0 1 1 2 3 5 8 13 21 34 55 89
Loop Control - break và continue
break - Thoát Loop
break thoát khỏi loop ngay lập tức.
# Tìm số đầu tiênnumbers = [1, 3, 5, 8, 10, 12]for num in numbers: if num % 2 == 0: print(f"Found even number: {num}") break# Found even number: 8 (dừng ngay) # Search in listnames = ["Alice", "Bob", "Charlie", "Diana"]search = "Charlie"found = False for name in names: if name == search: print(f"Found {search}!") found = True break if not found: print(f"{search} not found") # Break khỏi whilecount = 0while True: count += 1 if count > 5: break print(count)# 1, 2, 3, 4, 5
continue - Skip Iteration
continue bỏ qua iteration hiện tại, chuyển sang iteration tiếp theo.
# Skip số chẵnfor i in range(10): if i % 2 == 0: continue print(i, end=" ")# 1 3 5 7 9 # Skip negativenumbers = [1, -2, 3, -4, 5, -6]for num in numbers: if num < 0: continue print(num, end=" ")# 1 3 5 # Process valid itemsitems = ["apple", "", "banana", None, "orange", ""]for item in items: if not item: # Skip empty/None continue print(f"Processing: {item}")
else Clause trong Loop
else chạy khi loop kết thúc bình thường (không break).
# Tìm số nguyên tốnumber = 17for i in range(2, number): if number % i == 0: print(f"{number} is not prime") breakelse: print(f"{number} is prime") # Search với elsenames = ["Alice", "Bob", "Charlie"]search = "Diana" for name in names: if name == search: print(f"Found {search}") breakelse: print(f"{search} not found") # While với elsecount = 0while count < 5: print(count) count += 1else: print("Loop completed normally")
Nested Loops
Nested loops là loops bên trong loops.
# Basic nested loopfor i in range(3): for j in range(3): print(f"({i}, {j})", end=" ") print()# (0, 0) (0, 1) (0, 2)# (1, 0) (1, 1) (1, 2)# (2, 0) (2, 1) (2, 2) # Multiplication tablefor i in range(1, 6): for j in range(1, 11): print(f"{i}x{j}={i*j:2d}", end=" ") print() # Pattern printing# *# **# ***# ****for i in range(1, 5): for j in range(i): print("*", end="") print() # 2D list iterationmatrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] for row in matrix: for item in row: print(item, end=" ") print()
Break trong Nested Loops
# Break chỉ thoát inner loopfor i in range(3): for j in range(3): if j == 1: break print(f"({i}, {j})")# (0, 0), (1, 0), (2, 0) # Break cả outer loop (dùng flag)found = Falsefor i in range(3): for j in range(3): if i == 1 and j == 1: found = True break if found: break print(f"Row {i} complete")
List Comprehension vs Loop
# Traditional loopsquares = []for i in range(10): squares.append(i ** 2) # List comprehension (preferred)squares = [i ** 2 for i in range(10)] # With condition# Traditionalevens = []for i in range(10): if i % 2 == 0: evens.append(i) # List comprehensionevens = [i for i in range(10) if i % 2 == 0]
Ví Dụ Thực Tế
1. Sum và Average
numbers = [85, 90, 78, 92, 88] # Calculate sumtotal = 0for num in numbers: total += num average = total / len(numbers)print(f"Sum: {total}")print(f"Average: {average:.2f}") # Find max and minmax_val = numbers[0]min_val = numbers[0] for num in numbers: if num > max_val: max_val = num if num < min_val: min_val = num print(f"Max: {max_val}")print(f"Min: {min_val}") # Hoặc dùng built-inprint(f"Sum: {sum(numbers)}")print(f"Max: {max(numbers)}")print(f"Min: {min(numbers)}")
2. Menu System
def show_menu(): print("\n=== Menu ===") print("1. Add item") print("2. View items") print("3. Delete item") print("4. Exit") items = [] while True: show_menu() choice = input("Choose option: ") if choice == "1": item = input("Enter item: ") items.append(item) print(f"Added: {item}") elif choice == "2": if items: print("\nItems:") for i, item in enumerate(items, 1): print(f" {i}. {item}") else: print("No items") elif choice == "3": if items: for i, item in enumerate(items, 1): print(f" {i}. {item}") idx = int(input("Delete index: ")) - 1 if 0 <= idx < len(items): deleted = items.pop(idx) print(f"Deleted: {deleted}") else: print("No items to delete") elif choice == "4": print("Goodbye!") break else: print("Invalid choice")
3. Password Validator
def validate_password(password): """Validate password strength""" # Requirements min_length = 8 has_upper = False has_lower = False has_digit = False has_special = False # Check length if len(password) < min_length: return False, "Too short (min 8 characters)" # Check characters for char in password: if char.isupper(): has_upper = True elif char.islower(): has_lower = True elif char.isdigit(): has_digit = True elif char in "!@#$%^&*": has_special = True # Validate if not has_upper: return False, "Need uppercase letter" if not has_lower: return False, "Need lowercase letter" if not has_digit: return False, "Need digit" if not has_special: return False, "Need special character" return True, "Strong password" # Testpasswords = ["weak", "Password1", "Pass123!", "StrongP@ss1"]for pwd in passwords: valid, message = validate_password(pwd) status = "✓" if valid else "✗" print(f"{status} {pwd:<15} - {message}")
4. Pattern Printing
# Trianglen = 5print("Right Triangle:")for i in range(1, n + 1): print("*" * i) # Inverted Triangleprint("\nInverted Triangle:")for i in range(n, 0, -1): print("*" * i) # Pyramidprint("\nPyramid:")for i in range(1, n + 1): spaces = " " * (n - i) stars = "*" * (2 * i - 1) print(spaces + stars) # Diamondprint("\nDiamond:")# Upper halffor i in range(1, n + 1): print(" " * (n - i) + "*" * (2 * i - 1))# Lower halffor i in range(n - 1, 0, -1): print(" " * (n - i) + "*" * (2 * i - 1)) # Number patternprint("\nNumber Pattern:")for i in range(1, 6): for j in range(1, i + 1): print(j, end=" ") print()
5. Prime Number Finder
def is_prime(n): """Check if number is prime""" if n < 2: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True # Find all primes up to 100primes = []for num in range(2, 101): if is_prime(num): primes.append(num) print(f"Primes up to 100: {len(primes)}")print(primes) # Print in rows of 10print("\nFormatted:")for i, prime in enumerate(primes): print(f"{prime:3d}", end=" ") if (i + 1) % 10 == 0: print()
6. Shopping Cart
cart = [] while True: print("\n=== Shopping Cart ===") print("1. Add item") print("2. View cart") print("3. Calculate total") print("4. Checkout") print("5. Exit") choice = input("Choose: ") if choice == "1": name = input("Product name: ") price = float(input("Price: ")) qty = int(input("Quantity: ")) cart.append({"name": name, "price": price, "qty": qty}) print(f"Added {qty}x {name}") elif choice == "2": if not cart: print("Cart is empty") else: print("\nYour Cart:") for i, item in enumerate(cart, 1): subtotal = item["price"] * item["qty"] print(f"{i}. {item['name']:<15} ${item['price']:.2f} x{item['qty']} = ${subtotal:.2f}") elif choice == "3": total = sum(item["price"] * item["qty"] for item in cart) print(f"\nTotal: ${total:.2f}") elif choice == "4": if cart: print("\n=== Checkout ===") total = 0 for item in cart: subtotal = item["price"] * item["qty"] total += subtotal print(f"{item['name']:<15} ${subtotal:.2f}") print(f"\nTotal: ${total:.2f}") print("Thank you for shopping!") cart.clear() else: print("Cart is empty") elif choice == "5": print("Goodbye!") break
Performance Tips
# 1. Avoid modifying list while iterating# ❌ Saiitems = [1, 2, 3, 4, 5]for item in items: if item % 2 == 0: items.remove(item) # Dangerous! # ✅ Đúngitems = [item for item in items if item % 2 != 0] # 2. Use enumerate thay vì range(len())# ❌ Không tốtfruits = ["apple", "banana", "orange"]for i in range(len(fruits)): print(f"{i}: {fruits[i]}") # ✅ Tốt hơnfor i, fruit in enumerate(fruits): print(f"{i}: {fruit}") # 3. Use built-in functions# ❌ Chậmtotal = 0for num in numbers: total += num # ✅ Nhanh hơntotal = sum(numbers)
Bài Tập Thực Hành
Bài 1: Factorial
Tính n! (factorial) bằng loop.
Bài 2: Fibonacci
In n số Fibonacci đầu tiên.
Bài 3: Palindrome
Check string có phải palindrome không (đọc xuôi = đọc ngược).
Bài 4: Guess Number
Game đoán số:
- Random số từ 1-100
- User đoán
- Hint: too high/too low
- Count attempts
Bài 5: Pattern
Print pattern:
* *** ***** ****************
Tóm Tắt
✅ For loop: for item in iterable
✅ range(): range(start, stop, step)
✅ enumerate(): Loop với index
✅ zip(): Kết hợp nhiều iterables
✅ While loop: while condition:
✅ break: Thoát loop
✅ continue: Skip iteration
✅ else: Chạy khi loop kết thúc bình thường
✅ Nested loops: Loop trong loop
Bài Tiếp Theo
Bài 11: Functions - Định nghĩa functions, parameters, return values, scope, và lambda functions.
Remember:
- For loop cho iterables, while loop cho conditions
enumerate()tốt hơnrange(len())breakthoát loop,continueskip iteration- Avoid modifying list while iterating
- List comprehension thường tốt hơn loop đơn giản
- Practice để master loops!