Trường ĐH Công nghệ – Đại học Quốc gia Hà Nội
Chương trình đơn giản: Các lệnh chạy cố định thứ tự qua mỗi lần chạy.
Thực tế: Ta cần lựa chọn dựa trên dữ liệu vào.
Nếu đang ở vị trí hoa thì hút mật, ngược lại làm mật.
Cú pháp
if <biểu-thức-Boolean>:
<câu-lệnh-1>
<câu-lệnh-2>
...
<câu-lệnh-n>
Nếu x chẵn thì in even, ngược lại không làm gì.
x = 10
if x % 2 == 0:
print('even')
Khai báo các biến:
is_rainy = False # Giá trị kiểu Boolean
is_windy = True # Giá trị kiểu Boolean
temp = 12 # Giá trị kiểu số nguyên
Biến Boolean:
if is_rainy:
print("Hãy mang ô!")
Phép toán Boolean:
if is_windy and not is_rainy:
print("Đi thả diều nào!")
Toán tử so sánh:
if temp < 10 and is_rainy:
print("Hãy mặc áo khoác chống thấm nước!")
if temp >= 30:
print("Uống nhiều nước!")
Cú pháp:
if <biểu-thức-Boolean>:
<câu-lệnh>
...
else:
<câu-lệnh>
...
Ví dụ:
if x % 2 == 0:
print('even')
else:
print('odd')
| Cấu trúc chương trình | Luồng chương trình | |
|---|---|---|
| Định nghĩa | Cách mã được trình bày trong tệp. | Thứ tự thực thi lệnh khi chạy. |
| Thứ tự / Nhánh | Thứ tự dòng, mức thụt lề. | Không trùng với cấu trúc; có thể bỏ qua nhánh. |
| Phạm vi | Định nghĩa các khả năng qua nhiều lần chạy. | Định nghĩa điều gì xảy ra trong một lần chạy. |
# odd_even.py
x = 10
if x % 2 == 0:
print("even")
else:
print("odd")
print("odd") xuất hiện trong cấu trúc chương trình.
$ python odd_even.py
even
Luồng chạy khiến print("odd") được thực thi 0 lần.
a = 0
if a == 0:
b = a + 1 # b được tạo ở đây nếu nhánh này chạy
print(b) # b vẫn tồn tại sau if nếu đã được gán
Biến được tạo chỉ khi lệnh gán tương ứng thực sự được thực thi.
if <biểu-thức>:
<câu-lệnh>
...
elif <biểu-thức>:
<câu-lệnh>
...
elif <biểu-thức>:
<câu-lệnh>
...
else:
<câu-lệnh>
...
score = 80
if score >= 90:
print("Excellent!")
elif score >= 70:
print("Good job!")
elif score >= 50:
print("Pass.")
else:
print("Fail.")
x = 0
if x == 0:
print("x is 0!")
if x == 0:
print("still 0!")
if x == 0:
print("even still 0")
x is 0!
still 0!
even still 0
x = 0
if x == 0:
print("x is 0!")
elif x == 0:
print("still 0!")
elif x == 0:
print("even still 0")
x is 0!
Chuỗi if & elif đảm bảo chỉ một nhánh được chọn.
if raining and freezing:
print('Wear a waterproof coat.')
elif raining and not freezing:
print('Bring an umbrella.')
elif not raining and freezing:
print('Wear a warm coat!')
else:
print('A sweater will suffice.')
if raining:
if freezing:
print('Wear a waterproof coat.')
else:
print('Bring an umbrella.')
else:
if freezing:
print('Wear a warm coat!')
else:
print('A sweater will suffice.')
# determine winner
if x_score > y_score:
winner = "x"
else:
winner = "y"
Có thể dùng print() để truy vết luồng chương trình và theo dõi giá trị biến:
Truy vết (Trace) = in ra “dấu vết”.
# determine winner
print('before if') # TRACE: truy vết vị trí trước if
if x_score > y_score:
print('inside if') # TRACE: truy vết vị trí trong if
winner = "x"
else:
print('inside else') # TRACE: truy vết vị trí trong else
winner = "y"
print('after if')
Kết quả mẫu:
before if
inside if
after if
Từ dấu vết trên, suy ra: x_score > y_score.
# determine winner
print('before if') # TRACE: truy vết vị trí trước if
if x_score > y_score:
print('inside if') # TRACE: truy vết vị trí trong if
winner = "x"
print('winner =', winner) # WATCH: xem giá trị winner
else:
print('inside else') # TRACE: truy vết vị trí trong else
winner = "y"
print('winner =', winner) # WATCH: xem giá trị winner
print('after if') # TRACE: truy vết vị trí sau if
→ Dùng cả 2 để biết khối nào chạy và biến đang mang giá trị gì.
Kiểm thử = chạy chương trình với dữ liệu cụ thể để:
Mục tiêu: bao phủ nhanh, bắt lỗi ngưỡng, tối ưu công sức.
Quy tắc: Trả bình thường ≤ 40h; phần vượt 40h trả 1.5×.
def weekly_pay(hours, rate):
if hours <= 40:
return hours * rate
overtime = hours - 40
return 40 * rate + overtime * rate * 1.5
if score >= 90:
print("Excellent!")
elif score >= 70:
print("Good job!")
elif score >= 50:
print("Pass.")
else:
print("Fail.")
Thiết kế test: 4 ca, mỗi ca dẫn đến một nhánh khác nhau.
Ví dụ: 91, 80, 55, 40.
if raining:
if freezing:
print('Wear a waterproof coat.')
else:
print('Bring an umbrella.')
else:
if freezing:
print('Wear a warm coat!')
else:
print('A sweater will suffice.')
Thiết kế test: 4 ca tương ứng mọi kết hợp:
(raining, freezing) =
(True, True), (True, False),
(False, True), (False, False).
Bạn có nhớ trò chơi Scratch nho nhỏ này?
def move_forward():
print("move forward")
def turn_left():
print("turn_left")
move_forward()
move_forward()
turn_left()
move_forward()
move_forward()
Định nghĩa hàm
def move_forward():
print("move forward")
def turn_left():
print("turn_left")
Gọi hàm
move_forward()
move_forward()
turn_left()
move_forward()
move_forward()
Kết quả: Mỗi lần gọi hàm sẽ thực thi khối lệnh bên trong hàm đó.
move forward
move forward
turn_left
move forward
move forward
Tham số: giá trị truyền vào hàm khi gọi.
def what_to_wear(raining, freezing):
if raining:
if freezing:
# ... truncated
else:
if freezing:
# ... truncated
Hàm what_to_wear có hai tham số: raining và freezing.
what_to_wear(True, False)
what_to_wear(True, True)
what_to_wear(False, False)
what_to_wear(raining=False, freezing=True)
def what_to_wear(raining, freezing):
if raining:
if freezing:
return "Waterproof coat"
else:
return "Umbrella"
else:
if freezing:
return "Warm coat"
else:
return "Sweater"
today_outfit = what_to_wear(True, False)
sunny_day_outfit = what_to_wear(False, False)
Module = tập hợp hàm (và biến) trong một file .py.
# sample_functions.py
def what_to_wear(raining, freezing):
if raining:
if freezing:
return "Waterproof coat"
else:
return "Umbrella"
else:
# ... truncated
Dùng import để nhập module vào chương trình.
from sample_functions import what_to_wear
today_outfit = what_to_wear(True, False)
$ python
Python 3.13.7 | packaged by conda-forge | (main, Sep 3 2025, 14:33:26) [Clang 19.1.7 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from sample_functions import what_to_wear
>>> print_what_to_wear(True, False)
Wear a waterproof coat.