Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีใช้ Variable-length Arguments ใน Function Python

ใช้ *args (single asterisk) รับ non-keyword variable-length arguments เป็น list

ตัวอย่าง

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

multiply(3, 7)        # 21
multiply(9, 8)        # 72
multiply(3, 4, 7)     # 84
multiply(5, 6, 10, 8) # 2400

สำคัญ: * คือสัญลักษณ์ pack arguments เข้า list