多個參數與回傳值

Python 函式入門

Hugo Bowne-Anderson

Instructor

多個函式參數

  • 接受超過 1 個參數:
def raise_to_power(value1, value2):
    """Raise value1 to the power of value2."""
    new_value = value1 ** value2
    return new_value
  • 呼叫函式:引數數量 = 參數數量
result = raise_to_power(2, 3)

print(result)
8
Python 函式入門

快速認識 Tuple

  • 讓函式回傳多個值:使用 Tuple!

  • Tuple:

    • 類似 list,可包含多個值

    • 不可變,不能修改內容!

    • 用括號()建立

even_nums = (2, 4, 6)

print(type(even_nums))
<class 'tuple'>
Python 函式入門

拆解(Unpack)tuple

  • 將一個 tuple 拆成多個變數:
even_nums = (2, 4, 6)

a, b, c = even_nums
print(a)
2
print(b)
4
print(c)
6
Python 函式入門

存取 tuple 元素

  • 存取 tuple 元素的方式與 list 相同:
even_nums = (2, 4, 6)

print(even_nums[1])
4
second_num = even_nums[1]

print(second_num)
4
  • 使用從 0 起算的索引
Python 函式入門

回傳多個值

def raise_both(value1, value2):
    """Raise value1 to the power of value2
    and vice versa."""

    new_value1 = value1 ** value2
    new_value2 = value2 ** value1

    new_tuple = (new_value1, new_value2)

    return new_tuple
result = raise_both(2, 3)

print(result)
(8, 9)
Python 函式入門

一起來練習吧!

Python 函式入門

Preparing Video For Download...