While Loop
Vòng lặp while trong Python được sử dụng để thực thi một khối lệnh miễn là điều kiện còn đúng.
1️⃣ Cú pháp cơ bản
✅ Ví dụ: In số từ 1 đến 5
i = 1
while i <= 5:
print(i)
i += 1 # Tăng i để tránh vòng lặp vô hạn2️⃣ **while** với điều kiện nhập dữ liệu
password = ""
while password != "1234":
password = input("Enter password: ")
print("Access granted!")✅ Giải thích: hương trình tiếp tục yêu cầu nhập mật khẩu cho đến khi đúng.
3️⃣ Sử dụng **break** để dừng vòng lặp
Dùng break để thoát khỏi vòng lặp khi điều kiện thỏa mãn.
i = 1
while i <= 10:
print(i)
if i == 5:
break # Dừng khi i == 5
i += 14️⃣ Sử dụng **continue** để bỏ qua lần lặp hiện tại
Dùng continue để bỏ qua phần còn lại của vòng lặp và chạy vòng tiếp theo.
i = 0
while i < 5:
i += 1
if i == 3:
continue # Bỏ qua 3
print(i)5️⃣ **while** với **else**
Nếu vòng lặp kết thúc bình thường (không bị break), khối else sẽ chạy.
i = 1
while i <= 3:
print(i)
i += 1
else:
print("Loop finished!")
# Output:
# 1
# 2
# 3
# Loop finished!Nếu vòng lặp bị break, else không chạy:
i = 1
while i <= 3:
print(i)
if i == 2:
break
i += 1
else:
print("Loop finished!")
# Output:
# 1
# 26️⃣ Vòng lặp vô hạn
Nếu không có điều kiện dừng, vòng lặp sẽ chạy mãi mãi:
python
CopyEdit
while True:
user_input = input("Type 'exit' to stop: ")
if user_input == "exit":
break✅ Giải thích: while True tạo vòng lặp vô hạn, chỉ dừng khi nhập "exit".
For Loops
Basic **for** loop with a list
for i in [0, 1, 2]:
print("meow")✅ Cách tốt hơn: Dùng range()
for i in range(3): # Tự động tạo danh sách [0, 1, 2]
print("meow")✅ Dùng **_** nếu biến **i** không quan trọng
for _ in range(3):
print("meow")✅ Dùng chuỗi nhân với số (*****)
print("meow\n" * 3, end="") # Output: meow trên 3 dòng**Lists** trong Python
Danh sách lưu nhiều giá trị cùng một lúc.
students = ["Hermione", "Harry", "Ron"]✅ Duyệt **list** bằng vòng lặp **for**
for student in students:
print(student)✅ Duyệt danh sách bằng **range(len())** nếu cần chỉ số
for i in range(len(students)):
print(i + 1, students[i]) # In ra vị trí và tên**Dictionaries** (Từ điển)
Dùng để lưu dữ liệu theo key-value.
✅ Cách tạo **dict**
students = {
"Hermione": "Gryffindor",
"Harry": "Gryffindor",
"Ron": "Gryffindor",
"Draco": "Slytherin",
}✅ Truy xuất giá trị
print(students["Hermione"]) # Output: Gryffindor✅ Duyệt qua **dict**
for student in students:
print(student, students[student], sep=", ")✅ Dùng **list** chứa **dict**
students = [
{"name": "Hermione", "house": "Gryffindor", "patronus": "Otter"},
{"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
{"name": "Ron", "house": "Gryffindor", "patronus": "Jack Russell terrier"},
{"name": "Draco", "house": "Slytherin", "patronus": None},
]
for student in students:
print(student["name"], student["house"], student["patronus"], sep=", ")