Nội dung bài họcLesson content
Câu lệnh if/else trong Pythonif/else statements in Python
Python dùng if/elif/else để kiểm tra điều kiện. Lưu ý: dùng dấu hai chấm ":" sau điều kiện và thụt lề (indent) 4 khoảng trắng cho khối lệnh bên trong. Đây là điểm khác biệt với Scratch — Python dùng thụt lề thay vì khối.Python uses if/elif/else to check conditions. Note: use a colon ":" after the condition and indent 4 spaces for the block inside. This differs from Scratch — Python uses indentation instead of blocks.
tuoi = 18
if tuoi >= 18:
print("Bạn là người lớn")
elif tuoi >= 13:
print("Bạn là thanh thiếu niên")
else:
print("Bạn là trẻ em")
Vòng lặp forThe for loop
Vòng lặp for trong Python dùng range() để lặp n lần. Ví dụ: for i in range(5) sẽ lặp 5 lần, i chạy từ 0 đến 4. For cũng có thể lặp qua danh sách: for ten in ["An", "Bình", "Cường"].The for loop in Python uses range() to repeat n times. For example: for i in range(5) repeats 5 times, i goes from 0 to 4. For can also loop through a list: for name in ["An", "Binh", "Cuong"].
for i in range(5):
print("Lần lặp thứ", i)
# In ra 0, 1, 2, 3, 4
# Lặp qua danh sách
ten = ["An", "Bình", "Cường"]
for t in ten:
print("Xin chào", t)
Vòng lặp whileThe while loop
Vòng lặp while lặp khi điều kiện còn đúng. Khác với for (lặp n lần cố định), while lặp không xác định. CẨN THẬN: nếu điều kiện không bao giờ sai, while sẽ lặp vô hạn → treo máy. Đảm bảo thay đổi biến bên trong vòng lặp.The while loop repeats as long as the condition is true. Unlike for (fixed n times), while loops an indefinite number of times. WARNING: if the condition never becomes false, while will loop infinitely → freezes. Make sure to change a variable inside the loop.
diem = 0
while diem < 10:
print("Điểm hiện tại:", diem)
diem = diem + 1
print("Đã đạt 10 điểm!")
Game đoán sốNumber guessing game
Game đoán số dùng while + if/else. Máy tính chọn số ngẫu nhiên 1-100. Người dùng đoán. Nếu đoán nhỏ hơn → "lớn hơn", lớn hơn → "nhỏ hơn", đúng → "Chúc mừng!". Lặp while cho đến khi đoán đúng.A number guessing game uses while + if/else. The computer picks a random number 1-100. The user guesses. If guess is too low → "higher", too high → "lower", correct → "Congratulations!". Loop while until guessed correctly.
import random
so_bi_mat = random.randint(1, 100)
doan = 0
while doan != so_bi_mat:
doan = int(input("Đoán số 1-100: "))
if doan < so_bi_mat:
print("Lớn hơn!")
elif doan > so_bi_mat:
print("Nhỏ hơn!")
print("Chúc mừng! Đáp án là", so_bi_mat)