使用者自訂函式

Python 函式入門

Hugo Bowne-Anderson

Instructor

你將學到:

  • 定義無參數的函式

  • 定義單一參數的函式

  • 定義會回傳值的函式

  • 之後:多個參數、多個回傳值

Python 函式入門

內建函式

  • str()
x = str(5)

print(x)
'5'
print(type(x))
<class 'str'>
Python 函式入門

定義函式

def square():    # <- Function header

new_value = 4 ** 2 # <- Function body print(new_value)
square()
16
Python 函式入門

函式參數

def square(value):
    new_value = value ** 2
    print(new_value)

square(4)
16
square(5)
25
Python 函式入門

函式的回傳值

  • 用 return 從函式回傳值
def square(value):
    new_value = value ** 2
    return new_value

num = square(4) print(num)
16
Python 函式入門

Docstring

  • Docstring 說明函式的用途

  • 作為函式的文件註解

  • 放在函式標頭的下一行

  • 以三個雙引號 """ 包起來

def square(value):
    """Returns the square of a value."""
    new_value = value ** 2
    return new_value
Python 函式入門

一起來練習吧!

Python 函式入門

Preparing Video For Download...