預設與彈性引數

Python 函式入門

Hugo Bowne-Anderson

Instructor

你將學到:

  • 撰寫含預設引數的函式

  • 使用彈性引數

    • 對函式傳入任意數量的引數
Python 函式入門

加入預設引數

def power(number, pow=1):
   """Raise number to the power of pow."""
   new_value = number ** pow
   return new_value

power(9, 2)
81
power(9, 1)
9
power(9)
9
Python 函式入門

彈性引數:*args(1)

def add_all(*args):
    """Sum all values in *args together."""

    # Initialize sum
    sum_all = 0

    # Accumulate the sum
    for num in args:
        sum_all += num

    return sum_all
Python 函式入門

彈性引數:*args(2)

add_all(1)
1
add_all(1, 2)
3
add_all(5, 10, 15, 20)
50
Python 函式入門

彈性引數:**kwargs

print_all(name="Hugo Bowne-Anderson", employer="DataCamp")
name: Hugo Bowne-Anderson
employer: DataCamp
Python 函式入門

彈性引數:**kwargs

def print_all(**kwargs):
    """Print out key-value pairs in **kwargs."""

    # Print out the key-value pairs
    for key, value in kwargs.items():
        print(key + ": " + value)
print_all(name="dumbledore", job="headmaster")
job: headmaster
name: dumbledore
Python 函式入門

一起來練習吧!

Python 函式入門

Preparing Video For Download...