def
這幾種要素組合起來就會是個function
def fib(n):
"""Print a Fibonacci series up to n."""
output, next_result = 0, 1
while output < n:
print(output, end=' ')
output, next_result = next_result, output+next_result
print()
fib(500)
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
try:
print(output)
except NameError as e:
print( "Name Error:: {0}".format(e) )
try:
print(n)
except NameError as e:
print( "Name Error:: {0}".format(e) )
# Name Error:: name 'output' is not defined
# Name Error:: name 'n' is not defined
print( "type of fib: {}".format(type(fib)) )
# type of fib: <class 'function'>
fib
n
n
, output
, next_result
需要注意的是python使用的機制是call by object reference
,因此,需要特別注意傳入的參數的mutable
性質。
call by object reference would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it (items inserted into a list).
俗話說,行不改名坐不改姓,但在python的世界當中,function可以改名
my_fib = fib
my_fib(1000)
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
在function中若沒有使用retrun
語法,預設會回傳None
# if no return syntax
print( "return value:{}".format(fib(500)) )
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
# return value:None