Python trung cấp dành cho nhà phát triển
Jasmin Ludolf
Senior Data Science Content Developer
# Tạo hàm tùy chỉnh
def average(values):
# Tính trung bình
average_value = sum(values) / len(values)
# Làm tròn kết quả
rounded_average = round(average_value, 2)
# Trả về rounded_average
return rounded_average
values = Đối số# Làm tròn pi đến 2 chữ số
print(round(3.1415926535, 2))
3.14
Truyền đối số bằng cách gán giá trị cho keywords
Hữu ích để diễn giải và theo dõi đối số
# Làm tròn pi đến 2 chữ số
print(round(number=3.1415926535
Truyền đối số bằng cách gán giá trị cho keywords
Hữu ích để diễn giải và theo dõi đối số
# Làm tròn pi đến 2 chữ số
print(round(number=3.1415926535, ndigits=2))
3.14
# Tìm hiểu thêm về hàm trợ giúp
print(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.
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.
$$
numberndigitsHelp 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.
None = không có giá trị / rỗng
Đối số mặc định: cách đặt giá trị default cho một argument
Ghi đè None thành 2
Giá trị dùng thường xuyên - đặt bằng đối số mặc định
# Tạo hàm tùy chỉnh
def average(values):
average_value = sum(values) / len(values)
rounded_average = round(average_value, 2)
return rounded_average
# Tạo hàm tùy chỉnh def average(values, rounded=False):
# Tạo hàm tùy chỉnh def average(values, rounded=False):# Làm tròn đến hai chữ số thập phân nếu rounded là True if rounded == True:average_value = sum(values) / len(values) rounded_average = round(average_value, 2) return rounded_average
# Tạo hàm tùy chỉnh def average(values, rounded=False):# Làm tròn đến hai chữ số thập phân nếu rounded là True if rounded == True: average_value = sum(values) / len(values) rounded_average = round(average_value, 2) return rounded_average# Ngược lại, không làm tròn else: average_value = sum(values) / len(values) return average_value
# Danh sách thời gian chuẩn bị (phút)
preparation_times = [19.23, 15.67, 48.57, 23.45, 12.06, 34.56, 45.67]
# Lấy giá trị trung bình không làm tròn
print(average(preparation_times, False))
28.4585714
# Lấy giá trị trung bình không làm tròn
print(average(preparation_times))
28.4585714
# Lấy giá trị trung bình đã làm tròn
print(average(values=preparation_times, rounded=True))
28.46
Python trung cấp dành cho nhà phát triển