Trường ĐH Công nghệ – Đại học Quốc gia Hà Nội
>>> x = 5
>>> y = 4
>>> bigger = max(x, y)
>>> bigger
5
>>> pi = 3.14159
>>> a = round(pi, 2)
>>> a
3.14
VD: max() và round() là hàm dựng sẵn.
>>> x = 5
>>> y = 4
>>> bigger = max(x, y)
>>> bigger
5
>>> pi = 3.14159
>>> a = round(pi, 2)
>>> a
3.14
Làm sao biết một hàm làm gì? → Đọc tài liệu.
Sử dụng help() để xem tài liệu hàm trong chế độ tương tác:
>>> help(round)
Help on built-in function round in module builtins:
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
Tài liệu hàm round() từ Python docs:
Mục tiêu: đổi inch sang feet.
def inches_to_feet(inches):
return inches/12
def <tên_hàm>(<tham_số1>, ...):
<các_lệnh>
💡 def là từ khóa đặc biệt.
def inches_to_feet(inches):
return inches/12
if __name__ == "__main__":
inches_to_feet(65)
return <biểu_thức>
💡 return cũng là một từ khóa đặc biệt.
Q: Sự khác nhau giữa return và print()?
→ return là câu lệnh di chuyển dữ liệu trong bộ nhớ; print() là hàm hiển thị ký tự lên màn hình.
Q: Nếu một hàm không có return thì sao?
→ Việc thực thi kết thúc ở dòng cuối của hàm và trả về giá trị đặc biệt None.
Q: Nếu còn câu lệnh sau return thì sao?
→ Chúng sẽ bị bỏ qua.
def func_b():
print("func b")
def func_a():
print("func a")
func_b()
if __name__ == "__main__":
func_a()
counter = 0 # biến toàn cục
def show_counter():
print("Current counter:", counter)
def bad_increment():
counter = counter + 1 # UnboundLocalError
print("Bad_increment:", counter)
def good_increment():
global counter # khai báo dùng biến toàn cục
counter = counter + 1
print("Good_increment:", counter)
Tập hợp biến & hàm để tổ chức và tái sử dụng.
>>> import math
>>> math.pi
3.141592653589793
>>> p = math.sqrt(25)
5
Lưu mã vào tệp .py → tên mô-đun = tên tệp.
"""Thông tin UET-VNU."""
# Biến toàn cục
university_name = "UET - VNU"
def get_address():
"""Trả về địa chỉ của trường."""
return "144 Xuân Thủy"
(Ví dụ: uet_info.py)
import uet_info
if __name__ == "__main__":
print(uet_info.university_name)
print(uet_info.get_address())
>>> import uet_info
>>> uet_info.university_name
'UET - VNU'
def inches_to_feet(inches):
"""
Trả về số feet tương ứng với số inch cho trước.
Tham số:
inches (float|int): giá trị cần đổi.
Trả về:
float: feet.
"""
return inches/12
Docstring dùng dấu nháy ba; hiển thị bởi help().
import math
def circle_area(radius):
"""
Trả về diện tích hình tròn bán kính radius.
Tham số:
radius (float): bán kính, phải >= 0.
Trả về:
float: diện tích.
"""
return math.pi * radius ** 2
assert <điều_kiện>, "Thông báo lỗi (tuỳ chọn)"
x = 10
assert x > 0, "x phải dương"
Kết quả: điều kiện đúng → chương trình chạy bình thường.
x = -1
assert x > 0, "x phải dương"
Kết quả: điều kiện sai → AssertionError.
Có đặc tả → viết ca kiểm thử trước; thân hàm có thể để trống.
Trả về số Fibonacci thứ n:
fib(0) = 0
fib(1) = 1
fib(2) = fib(1) + fib(0) = 1
fib(3) = fib(2) + fib(1) = 2
fib(n) = fib(n-1) + fib(n-2)
# test_fib.py
# fibonacci.py là tệp cài đặt hàm fib(n)
from fibonacci import fib
def test_first_two():
assert fib(0) == 0
assert fib(1) == 1
def test_small_numbers():
assert fib(2) == 1
assert fib(3) == 2
assert fib(4) == 3
def test_large_number():
assert fib(10) == 55
# test_fib.py (cuối file)
if __name__ == "__main__":
test_first_two()
test_small_numbers()
test_large_number()
# fibonacci.py
def fib(n):
"""
Trả về số Fibonacci thứ n.
Tham số:
n (int): vị trí trong dãy Fibonacci.
Trả về:
int: số Fibonacci thứ n.
"""
return 0
Chạy test → thất bại (luôn trả về 0).
Hoàn thiện fib(n) để vượt qua tất cả kiểm thử trong test_fib.py.