Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách dùng variable-length arguments trong function Python?

Trong Python, single-asterisk form *args có thể dùng làm parameter để send non-keyworded variable-length argument list cho functions. Thấy rằng asterisk (*) quan trọng ở đây, và cùng với từ args có nghĩa là có variable length list của non-keyworded arguments.

Ví dụ

def multiply(*args):
    y = 1
    for num in args:
        y *= num
    print(y)

multiply(3, 7)
multiply(9, 8)
multiply(3, 4, 7)
multiply(5, 6, 10, 8)

Kết quả

21
72
84
2400