iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 11
0
  • def
  • function name
  • parameters
  • function internal implementation
  • return

這幾種要素組合起來就會是個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'>
  • function name: fib
  • parameters: n
  • local symbol table: 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

參考


上一篇
Day16-Built-in Types-Recap
下一篇
Day18-Function-Argument語法糖
系列文
if len(learning.python) == 30:31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言