Giới thiệu về Functions trong Python
Hugo Bowne-Anderson
Instructor
Không phải mọi đối tượng đều truy cập được ở mọi nơi trong script
Phạm vi (scope) - phần chương trình nơi một đối tượng hoặc tên có thể truy cập
Phạm vi toàn cục (global) - định nghĩa trong thân chính của script
Phạm vi cục bộ (local) - định nghĩa bên trong hàm
Phạm vi dựng sẵn (built-in) - các tên trong mô-đun builtins dựng sẵn
def square(value): """Returns the square of a number.""" new_val = value ** 2 return new_valsquare(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
new_val = 10 def square(value): """Returns the square of a number.""" new_val = value ** 2 return new_valsquare(3)
9
new_val
10
new_val = 10 def square(value): """Returns the square of a number.""" new_value2 = new_val ** 2 return new_value2square(3)
100
new_val = 20
square(new_val)
400
new_val = 10 def square(value): """Returns the square of a number.""" global new_val new_val = new_val ** 2 return new_valsquare(3)
100
new_val
100
Giới thiệu về Functions trong Python