Nội dung bài họcLesson content
Hàm với tham số và returnFunctions with parameters and return
Hàm có thể nhận nhiều tham số và trả về giá trị. def tinh_chu_vi(ban_kinh): return 2 * 3.14 * ban_kinh. Gọi: tinh_chu_vi(5). Tham số là đầu vào, return là đầu ra. Hàm có thể có nhiều return.Functions can take multiple parameters and return values. def calc_circumference(radius): return 2 * 3.14 * radius. Call: calc_circumference(5). Parameters are inputs, return is output. Functions can have multiple returns.
def tinh_dien_tich(chieu_dai, chieu_rong):
"""Tính diện tích hình chữ nhật"""
return chieu_dai * chieu_rong
# Gọi hàm với 2 tham số
s = tinh_dien_tich(10, 5)
print(f"Diện tích: {s}") # 50
Module math: hằng số và hàm toán họcThe math module: constants and math functions
Module math cung cấp: math.pi (π = 3.14159...), math.sqrt() (căn bậc 2), math.pow() (lũy thừa), math.ceil() (làm tròn lên), math.floor() (làm tròn xuống). Import math rồi dùng math.ten_ham().The math module provides: math.pi (π = 3.14159...), math.sqrt() (square root), math.pow() (power), math.ceil() (round up), math.floor() (round down). Import math then use math.function_name().
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(144)) # 12.0
print(math.pow(2, 10)) # 1024.0
print(math.ceil(4.1)) # 5
print(math.floor(4.9)) # 4
Module random: số ngẫu nhiênThe random module: random numbers
Module random tạo số ngẫu nhiên: random.randint(a, b) (số nguyên từ a đến b), random.random() (số thập phân 0-1), random.choice(list) (chọn ngẫu nhiên 1 phần tử). Dùng cho game, mô phỏng, mật khẩu.The random module generates random numbers: random.randint(a, b) (integer from a to b), random.random() (decimal 0-1), random.choice(list) (randomly pick 1 item). Used for games, simulations, passwords.
import random
# Số nguyên ngẫu nhiên 1-100
so = random.randint(1, 100)
print(f"Số ngẫu nhiên: {so}")
# Chọn ngẫu nhiên từ danh sách
hoa_qua = ["táo", "cam", "chuối", "xoài"]
chon = random.choice(hoa_qua)
print(f"Trái cây hôm nay: {chon}")
# Số thập phân 0-1
print(random.random()) # 0.37291...
Docstring: tài liệu hàmDocstrings: function documentation
Docstring là chuỗi mô tả hàm, đặt ngay sau dòng def. Dùng 3 dấu nháy. Docstring giúp người khác hiểu hàm làm gì. Dùng help(ten_ham) để xem docstring. Đây là thói quen tốt của lập trình viên chuyên nghiệp.A docstring is a string describing the function, placed right after the def line. Use triple quotes. Docstrings help others understand what the function does. Use help(function_name) to view it. This is a good professional habit.
def tinh_bmi(cannang, chieu_cao):
"""Tính chỉ số BMI
Args:
cannang: cân nặng (kg)
chieu_cao: chiều cao (m)
Returns:
chỉ số BMI
"""
return cannang / (chieu_cao ** 2)
print(tinh_bmi(60, 1.70)) # 20.76
help(tinh_bmi) # Hiển thị docstring