📖 Python Cơ bản - Hàm và Module trong Python
50 phút

Hàm và Module trong Python

Hàm (Functions)

Định nghĩa hàm

def greet(name):
    """Hàm chào hỏi"""
    return f"Xin chào {name}!"

def calculate_area(length, width):
    """Tính diện tích hình chữ nhật"""
    return length * width

# Gọi hàm
print(greet("John"))
print(calculate_area(5, 3))

Tham số mặc định

def introduce(name, age=25, city="Hà Nội"):
    """Hàm giới thiệu với tham số mặc định"""
    return f"Tôi là {name}, {age} tuổi, sống tại {city}"

print(introduce("John"))
print(introduce("Jane", 30, "TP.HCM"))

Module

Tạo và sử dụng module

# math_operations.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Lỗi: Chia cho 0!"
    return a / b

# main.py
import math_operations as mo

print(mo.add(10, 5))
print(mo.multiply(4, 7))

Module tích hợp

import math
import random
from datetime import datetime

# Sử dụng math module
print(math.sqrt(25))
print(math.pi)

# Sử dụng random module
print(random.randint(1, 10))
fruits = ["apple", "banana", "orange"]
print(random.choice(fruits))

# Sử dụng datetime
now = datetime.now()
print(f"Bây giờ là: {now}")

Bài tập thực hành

Hãy tạo các module tiện ích của riêng bạn!

📝 Bài tập (2)

  1. Tạo module chứa các hàm tính toán hình học

  2. Tạo module với các hàm xử lý chuỗi tiện ích

Bài học "Hàm và Module trong Python" - Khóa học "Python Cơ bản"