Đối số mặc định và linh hoạt

Giới thiệu về Functions trong Python

Hugo Bowne-Anderson

Instructor

Bạn sẽ học:

  • Viết hàm với đối số mặc định

  • Dùng đối số linh hoạt

    • Truyền số lượng đối số tùy ý vào hàm
Giới thiệu về Functions trong Python

Thêm đối số mặc định

def power(number, pow=1):
   """Lũy thừa number với số mũ pow."""
   new_value = number ** pow
   return new_value

power(9, 2)
81
power(9, 1)
9
power(9)
9
Giới thiệu về Functions trong Python

Đối số linh hoạt: *args (1)

def add_all(*args):
    """Cộng tất cả giá trị trong *args."""

    # Khởi tạo tổng
    sum_all = 0

    # Cộng dồn
    for num in args:
        sum_all += num

    return sum_all
Giới thiệu về Functions trong Python

Đối số linh hoạt: *args (2)

add_all(1)
1
add_all(1, 2)
3
add_all(5, 10, 15, 20)
50
Giới thiệu về Functions trong Python

Đối số linh hoạt: **kwargs

print_all(name="Hugo Bowne-Anderson", employer="DataCamp")
name: Hugo Bowne-Anderson
employer: DataCamp
Giới thiệu về Functions trong Python

Đối số linh hoạt: **kwargs

def print_all(**kwargs):
    """In ra các cặp khóa-giá trị trong **kwargs."""

    # In ra các cặp khóa-giá trị
    for key, value in kwargs.items():
        print(key + ": " + value)
print_all(name="dumbledore", job="headmaster")
job: headmaster
name: dumbledore
Giới thiệu về Functions trong Python

Ayo berlatih!

Giới thiệu về Functions trong Python

Preparing Video For Download...