# 變數範圍

>>> x = 10
>>> y = 10
>>> def some():
...     x = 20
...     print(x)
...     print(y)
...
>>> some()
20
10
>>> print(x)
10
>>> print(y)
10
>>>

>>> x = 20
>>> def some(x = x):
...     print(x)
...
>>> some()
20
>>> some(30)
30
>>> print(x)
20
>>>

• demo.py
``x = 10       　　# 全域def outer():   y = 20        # 在 outer() 函式範圍      def inner():       z = 30    # 在 inner() 函式範圍       print(x)  # 內建範圍 print，全域的 x   　　print(y)  # 內建範圍 print，外包 outer() 函式的 y      print(x)       # 內建範圍 print，全域的 x``

>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'Buffer
Error', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'Environme
ntError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'Generato
rExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexErr
or', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError',
'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'P
endingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', '
StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'Ta
bError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'Unicod
eEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserW
arning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_
class__', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs'
, 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'chr', 'classmetho
d', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'div
mod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozens
et', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int
', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map'
, 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'pr
int', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr'
, 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'va
rs', 'zip']
>>>

``import builtinsimport sysbuiltins.argv = sys.argvprint(argv[1])``

>>> x = 10
>>> def some():
...     global x
...     x = 20
...
>>> some()
>>> print(x)
20
>>>

>>> x = 10
>>> def some():
...     print(x)
...     x = 20
...
>>> some()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in some
UnboundLocalError: local variable 'x' referenced before assignment
>>>

>>> x = 10
>>> def some():
...     global x
...     print(x)
...     x = 20
...
>>> some()
10
>>>

``x = 10def outer():   x = 100         # 這是在 outer() 函式範圍的 x   def inner():       nonlocal x       x = 1000    # 改變的是 outer() 函式的 x   inner()   print(x)        # 顯示 1000outer()print(x)           # 顯示 10``

>>> def func():
...     x = 10
...     def getX():
...         return x
...     def setX(n):
...         x = n
...     return (getX, setX)
...
>>> getX, setX = func()
>>> getX()
10
>>> setX(20)
>>> getX()
10
>>>

>>> def func():
...     x = 10
...     def getX():
...         return x
...     def setX(n):
...         nonlocal x
...         x = n
...     return (getX, setX)
...
>>> getX, setX = func()
>>> getX()
10
>>> setX(20)
>>> getX()
20
>>>