變數範圍分為4種(LEGB)
global
關鍵字的變數global
關鍵字的變數builtins
module檢視var1 = 10
def demo(para1):
var2 = 100
print('var1 is {}, it\'s global in demo module(file)'.format(var1))
print('para1 is {}, it\' lobal in demo function'.format(para1))
print('var2 is {}, it\' lobal in demo function'.format(var2))
demo(50)
# var1 is 10, it's global in demo module(file)
# para1 is 50, it' lobal in demo function
# var2 is 100, it' lobal in demo function
try:
print('para1 is {}'.format(para1))
except NameError as e:
print('Name Error: {0}'.format(e))
try:
print('var2 is {}'.format(var2))
except NameError as e:
print('Name Error: {0}'.format(e))
# Name Error: name 'para1' is not defined
# Name Error: name 'var2' is not defined
def demo2(para2):
var3 = 66
global var5
var5 = 33
def demo3():
var3 = 22
var4 = 88
print('var3: {}'.format(var3))
print('var4: {}'.format(var4))
print('sum of var3 and var4: {}'.format(var3 + var4))
demo3()
demo2(10)
# var3: 22
# var4: 88
# sum of var3 and var4: 110
# var5: 33
demo3()
# NameError: name 'demo3' is not defined
builtins_name = dir(builtins)
print('{}'.format(builtins_name))
print('len of builtins_name is {}'.format(len(builtins_name)))
print('{}'.format('NameError' in builtins_name))
# ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', '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', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
# len of builtins_name is 151
# True