Cấp độ: elementary30 phútminMiễn phíFreeYoung CreatorYoung Creator

Python: Hàm và modulePython: Functions and modules

Bộ hàm tính toán họcA set of math calculation functions

Bạn sẽ học gìWhat you will learn

  • Định nghĩa và gọi hàmDefine and call functions
  • Dùng tham số và returnUse parameters and return
  • Import và dùng moduleImport and use modules

Bạn sẽ tạo gìWhat you will build

Bộ hàm tính toán họcA set of math calculation functions

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.

python
                      
                        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().

python
                      
                        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.

python
                      
                        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.

python
                      
                        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
                      
                    

Bài tập thực hànhHands-on exercises

1Viết hàm tinh_chu_vi(ban_kinh) dùng math.pi để tính chu vi hình tròn. Gọi với bán kính 7.Write a function tinh_chu_vi(radius) using math.pi to calculate circle circumference. Call with radius 7.

Gợi ýHint

Chu vi = 2 * math.pi * ban_kinhCircumference = 2 * math.pi * radius

Lời giảiSolution
python
                      
                        import math

def tinh_chu_vi(ban_kinh):
    return 2 * math.pi * ban_kinh

print(f"Chu vi: {tinh_chu_vi(7):.2f}")  # 43.98
                      
                    

2Viết hàm xuc_sac() trả về số ngẫu nhiên 1-6. Gọi 5 lần và in kết quả.Write a function xuc_sac() that returns a random number 1-6. Call 5 times and print results.

Gợi ýHint

Dùng random.randint(1, 6).Use random.randint(1, 6).

Lời giảiSolution
python
                      
                        import random

def xuc_sac():
    return random.randint(1, 6)

for i in range(5):
    print(f"Lần {i+1}: {xuc_sac()}")
                      
                    

Kiểm traQuiz

Chọn đáp án đúng cho mỗi câu. Nhấn để xem giải thích.Choose the correct answer for each question. Click to see explanation.

Câu 1: Lệnh nào trả về giá trị từ hàm?Q1: Which statement returns a value from a function?

Câu 2: math.sqrt(144) trả về gì?Q2: What does math.sqrt(144) return?

Câu 3: random.randint(1, 10) có thể trả về số nào?Q3: Which numbers can random.randint(1, 10) return?

Câu 4: Docstring đặt ở đâu trong hàm?Q4: Where is a docstring placed in a function?

Code mẫuSample code

python
                import math
import random

def tinh_chu_vi(ban_kinh):
    """Tính chu vi hình tròn / Calculate circle circumference"""
    return 2 * math.pi * ban_kinh

def so_ngau_nhien(min_val, max_val):
    """Số ngẫu nhiên / Random number"""
    return random.randint(min_val, max_val)

# Gọi hàm / Call functions
r = 5
print(f"Chu vi / Circumference: {tinh_chu_vi(r):.2f}")
print(f"Số ngẫu nhiên / Random: {so_ngau_nhien(1, 100)}")