global
定義「全局變數」:使在function區塊中定義的區域變數可以在整個程式中使用
>>>x = 6
>>>def func():
>>> global x
>>> x = 1
>>>
>>>func()
>>>print x
1The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.
>>>def bob():
>>> me = "locally defined"
>>> # Defined only in local context
>>> print me
>>>bob()
>>>print me
>>># Asking for a global variablelocally defined
Traceback (most recent call last):
File "file.py", line 9, in <module>
print me
NameError: name 'me' is not defined
While if you use the global statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.
Get 烏龜喵’s stories in your inbox
Join Medium for free to get updates from this writer.
在function區去中宣告global變數,執行該function之後,即可於function之外讀取該global變數
>>>def bob():
>>> global me
>>> me = "locally defined"
>>> # Defined locally but declared as global
>>> print me
>>>bob()
>>>print me
>>># Asking for a global variablelocally defined
locally defined







