Python 函式入門
Hugo Bowne-Anderson
Instructor
定義無參數的函式
定義單一參數的函式
定義會回傳值的函式
之後:多個參數、多個回傳值
str()x = str(5)
print(x)
'5'
print(type(x))
<class 'str'>
def square(): # <- Function headernew_value = 4 ** 2 # <- Function body print(new_value)square()
16
def square(value):
new_value = value ** 2
print(new_value)
square(4)
16
square(5)
25
def square(value): new_value = value ** 2 return new_valuenum = square(4) print(num)
16
Docstring 說明函式的用途
作為函式的文件註解
放在函式標頭的下一行
以三個雙引號 """ 包起來
def square(value):
"""Returns the square of a value."""
new_value = value ** 2
return new_value
Python 函式入門