作用域與自訂函式

Python 函式入門

Hugo Bowne-Anderson

Instructor

函式作用域速成

  • 並非所有物件在整個腳本都可存取

  • 作用域:程式中物件或名稱可被存取的範圍

    • 全域作用域:在腳本主體中定義

    • 區域作用域:在函式內定義

    • 內建作用域:預先定義的 built-ins 模組名稱

Python 函式入門

全域與區域作用域(1)

def square(value):
    """Returns the square of a number."""
    new_val = value ** 2
    return new_val

square(3)
9
new_val
<hr />----------------------------------------------------------------
NameError                       Traceback (most recent call last)
<ipython-input-3-3cc6c6de5c5c> in <module>()
<hr />-> 1 new_value
NameError: name 'new_val' is not defined
Python 函式入門

全域與區域作用域(2)

new_val = 10

def square(value):
    """Returns the square of a number."""
    new_val = value ** 2
    return new_val

square(3)
9
new_val
10
Python 函式入門

全域與區域作用域(3)

new_val = 10

def square(value):
    """Returns the square of a number."""
    new_value2 = new_val ** 2
    return new_value2

square(3)
100
new_val = 20

square(new_val)
400
Python 函式入門

全域與區域作用域(4)

new_val = 10

def square(value):
    """Returns the square of a number."""
    global new_val
    new_val = new_val ** 2
    return new_val

square(3)
100
new_val
100
Python 函式入門

一起來練習吧!

Python 函式入門

Preparing Video For Download...