26. Hàm
Khi chương trình của bạn ngày càng nhiều chức năng, việc viết hàng trăm dòng mã liên tục sẽ khiến mã nguồn trở nên rối rắm, khó đọc và khó bảo trì. Nếu có một đoạn mã cần sử dụng ở nhiều nơi (như việc tính toán hay kiểm tra dữ liệu), việc chép - dán (copy-paste) mã nhiều lần là cách làm không tối ưu.
Trong phần này, chúng ta sẽ tìm hiểu về hàm, để giúp việc lập trình được tối ưu hơn.
26.1 Định nghĩa và gọi hàm
Hàm (function) là một khối mã lệnh độc lập, được đặt tên và thực hiện một nhiệm vụ cụ thể. Bạn có thể gọi hàm chạy nhiều lần ở các vị trí khác nhau trong chương trình mà không cần phải viết lại mã nguồn.
Trong Python, bạn dùng từ khóa def để định nghĩa (tạo) một hàm.
Cú pháp:
def ten_ham(tham_so_1, tham_so_2, ...):
"""
Docstring: Mô tả chức năng của hàm (không bắt buộc)
"""
# Khối lệnh bên trong hàm (thụt lề 4 khoảng trắng)
câu_lệnh
return gia_tri_tra_ve # (Tùy chọn)
Ví dụ minh họa:
# 1. Định nghĩa hàm không có tham số và không có giá trị trả về
def xin_chao():
print("Chào bạn đến với khóa học lập trình python!")
# Gọi hàm thực thi
xin_chao()
# 2. Định nghĩa hàm có tham số truyền vào
def chao_nguoi_dung(ten):
print(f"Xin chào {ten}, chúc bạn một ngày vui!")
chao_nguoi_dung("Teo")
chao_nguoi_dung("Ti")
26.2 Giá trị trả về của hàm
Hàm có thể nhận dữ liệu vào (qua các tham số) và trả về kết quả cho chương trình chính bằng từ khóa return. Khi gặp câu lệnh return, hàm sẽ dừng lại ngay lập tức và chuyển giá trị đằng sau return về nơi gọi hàm.
Ví dụ minh họa:
def tinh_tong(a, b):
tong = a + b
return tong # Trả về kết quả
# Gọi hàm và lưu kết quả trả về vào một biến
ket_qua = tinh_tong(15, 25)
print(f"Tổng là: {ket_qua}") # Kết quả: 40
# Sử dụng trực tiếp kết quả trả về trong biểu thức
print(f"Tổng gấp đôi là: {tinh_tong(10, 20) * 2}") # Kết quả: 60
26.3 Tham số mặc định
Bạn có thể gán giá trị mặc định cho tham số khi định nghĩa hàm. Nếu người dùng gọi hàm mà không truyền giá trị cho tham số đó, Python sẽ tự động dùng giá trị mặc định.
Ví dụ minh họa:
def luy_thua(co_so, mu=2):
return co_so ** mu
print(luy_thua(5)) # Không truyền 'mu', tự động lấy mu=2 -> Kết quả: 25
print(luy_thua(2, 3)) # Truyền 'mu=3' -> Kết quả: 8
26.4 Phạm vi của biến
Biến trong Python được chia thành hai loại phạm vi chính dựa trên vị trí nơi nó được khai báo:
1. Biến cục bộ
Biến cục bộ (local variable) là biến được khai báo bên trong một hàm. Biến này chỉ tồn tại và được sử dụng trong nội bộ hàm đó. Khi hàm kết thúc, biến cục bộ sẽ bị xóa khỏi bộ nhớ.
Ví dụ:
def tinh_hieu():
x = 10 # x là biến cục bộ
print(f"Bên trong hàm x = {x}")
tinh_hieu()
# print(x) # Lỗi! NameError: name 'x' is not defined (vì x không tồn tại ngoài hàm)
2. Biến toàn cục
Biến toàn cục (global variable) là biến được khai báo bên ngoài tất cả các hàm. Biến này có thể được đọc từ bất kỳ đâu trong chương trình.
Ví dụ:
diem_so = 10 # Biến toàn cục
def hien_thi_diem():
print(f"Điểm số hiện tại: {diem_so}") # Đọc biến toàn cục
hien_thi_diem()
Lưu ý: Nếu bạn muốn thay đổi giá trị của biến toàn cục từ bên trong một hàm, bạn phải sử dụng từ khóa global.
Ví dụ:
bo_dem = 0 # Biến toàn cục
def tang_bo_dem():
global bo_dem # Khai báo sử dụng biến toàn cục bo_dem
bo_dem += 1
tang_bo_dem()
tang_bo_dem()
print(f"Bộ đếm: {bo_dem}") # Kết quả: 2
26.5 Bài tập và câu hỏi
Bài tập
Bài 26a: Xây dựng các hàm toán học cho Máy tính cầm tay (calculator)
Mục tiêu: Chia nhỏ bài toán máy tính cầm tay thành các hàm chức năng xử lý riêng biệt.
Yêu cầu: Viết các hàm thực hiện từng tác vụ toán học cơ bản:
- cong(a, b): Trả về a+b
- tru(a, b): Trả về a-b
- nhan(a, b): Trả về ab
- chia(a, b): Trả về a/b (sử dụng try ... except để xử lý chia cho 0).
Viết chương trình cho người dùng chọn phép tính và nhập hai số để gọi hàm tương ứng.
Bài 26b: Hàm định dạng dòng lịch sử phép tính
Mục tiêu: Luyện tập viết hàm xử lý chuỗi và trả về giá trị.
Yêu cầu: Viết hàm tao_chuoi_lich_su(so_a, phep_tinh, so_b, ket_qua) nhận vào 4 tham số và trả về một chuỗi có cấu trúc chuẩn để lưu tập tin.
Ví dụ: Nhập (5, "+", 3, 8) Trả về chuỗi "5 + 3 = 8".
Bài 26c: Máy tính nâng cao hoàn chỉnh modular hóa
Mục tiêu: Tổng hợp kiến thức về hàm, try ... except, và thao tác trên tập tin.
Yêu cầu: Viết ứng dụng máy tính bỏ túi hoàn chỉnh sử dụng các hàm:
1. luu_lich_su(dong_van_ban): Ghi kết quả phép tính vào file lich_su.txt
2. xem_lich_su(): Đọc và hiển thị tất cả phép tính đã lưu từ tập tin lich_su.txt. Dùng try ... except bắt lỗi nếu chưa có tập tin
3. main(): Hàm chính quản lý menu lựa chọn (1: Tính toán, 2: Xem lịch sử, 3: Thoát)
Câu hỏi ôn tập
Câu 26.1: Từ khóa nào được sử dụng để định nghĩa một hàm trong ngôn ngữ Python?
A. function
B. def
C. func
D. create
Câu 26.2: Phát biểu nào sau đây về từ khóa return trong hàm là SAI?
A. return dùng để trả kết quả của hàm về nơi gọi hàm
B. Khi gặp câu lệnh return, hàm sẽ lập tức kết thúc thực thi
C. Một hàm bắt buộc phải chứa câu lệnh return
D. Một hàm có thể không có câu lệnh return (trả về None)
Câu 26.3: Tác dụng của từ khóa global bên trong một hàm là gì?
A. Tạo ra một biến mới hoàn toàn
B. Cho phép hàm thay đổi giá trị của một biến toàn cục đã khai báo bên ngoài
C. Khai báo hàm đó có thể gọi ở mọi tập tin
D. Chuyển kiểu dữ liệu của biến sang kiểu chuỗi
26. Functions
As your program grows and gains more functionality, writing hundreds of lines of continuous code will make your source code messy, difficult to read, and hard to maintain. If a block of code needs to be used in multiple places (such as performing a calculation or validating data), copying and pasting code repeatedly is an inefficient approach.
In this section, we will learn about functions to optimize our programming practice.
26.1 Function Definition and Invocation
A function is an independent block of code that is named and performs a specific task. You can call a function to execute multiple times at different locations throughout the program without rewriting the source code.
In Python, you use the def keyword to define (create) a function.
Syntax:
def function_name(parameter_1, parameter_2, ...):
"""
Docstring: Description of the function's task (optional)
"""
# Code block inside the function (indented by 4 spaces)
statement
return return_value # (Optional)
Examples:
# 1. Define a function with no parameters and no return value
def greet():
print("Welcome to the Python programming course!")
# Call the function to execute
greet()
# 2. Define a function with input parameters
def greet_user(name):
print(f"Hello {name}, have a great day!")
greet_user("John")
greet_user("Alice")
26.2 Return Values
A function can receive input data (via parameters) and return a result back to the main program using the return keyword. When a return statement is encountered, the function terminates immediately and sends the value following return back to the caller.
Examples:
def calculate_sum(a, b):
total = a + b
return total # Return the result
# Call the function and store the returned value in a variable
result = calculate_sum(15, 25)
print(f"Total is: {result}") # Result: 40
# Use the returned value directly within an expression
print(f"Doubled total is: {calculate_sum(10, 20) * 2}") # Result: 60
26.3 Default Parameters
You can assign default values to parameters when defining a function. If the user calls the function without passing a value for that parameter, Python will automatically use the default value.
Examples:
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 'exponent' is omitted, defaults to exponent=2 -> Result: 25
print(power(2, 3)) # 'exponent=3' is passed -> Result: 8
26.4 Variable Scope
Variables in Python are categorized into two main scope levels based on where they are declared:
1. Local Variables
A local variable is declared inside a function. It exists and can only be accessed within that function's local environment. When the function terminates, the local variable is deleted from memory.
def calculate_difference():
x = 10 # x is a local variable
print(f"Inside the function x = {x}")
calculate_difference()
# print(x) # Error! NameError: name 'x' is not defined (x does not exist outside the function)
2. Global Variables
A global variable is declared outside of all functions. It can be read from anywhere within the program.
score = 10 # Global variable
def display_score():
print(f"Current score: {score}") # Reads the global variable
display_score()
Note: If you want to modify the value of a global variable from inside a function, you must use the global keyword.
counter = 0 # Global variable
def increment_counter():
global counter # Declare use of the global variable counter
counter += 1
increment_counter()
increment_counter()
print(f"Counter: {counter}") # Result: 2
26.5 Exercises and Review Questions
Exercises
Exercise 26a: Implement Mathematical Functions for a Calculator
Objective: Modularize a calculator application into individual functional helper routines
Requirements: Write functions to perform basic mathematical operations:
- add(a, b): Returns a + b
- subtract(a, b): Returns a - b
- multiply(a, b): Returns a * b
- divide(a, b): Returns a / b (use try ... except to handle division by zero)
Write a main routine prompting the user to select an operation and enter two numbers to invoke the corresponding function.
Exercise 26b: Format Calculation History Line
Objective: Practice writing functions that perform string formatting and return values
Requirements: Create a function format_history_line(num_a, operator, num_b, result) accepting four parameters and returning a standardized formatted string suitable for file storage
Example: Passing (5, "+", 3, 8) returns the string "5 + 3 = 8"
Exercise 26c: Complete Modularized Advanced Calculator
Objective: Combine concepts of functions, try ... except, and file handling operations.
Requirements: Build a functional pocket calculator application using the following functions:
1. save_history(text_line): Appends the calculation result string to history.txt
2. view_history(): Reads and outputs all stored calculations from history.txt. Use try ... except to handle file-not-found scenarios
3. main(): Top-level control loop managing menu choices (1: Calculate, 2: View History, 3: Exit)
Review Questions
Question 26.1: Which keyword is used to define a function in Python?
A. function
B. def
C. func
D. create
Question 26.2: Which statement regarding the return keyword in a function is INCORRECT?
A. return passes the result of a function back to the caller
B. When a return statement is encountered, the function immediately terminates execution
C. A function is strictly required to contain a return statement
D. A function can lack a return statement (implicitly returning None)
Question 26.3: What is the purpose of using the global keyword inside a function?
A. Instantiates an entirely new variable
B. Permits the function to modify the value of an existing global variable declared outside
C. Declares that the function can be called across all project files
D. Casts the data type of the variable into a string.