變數作用域 === Python 修改全域變數時不像其他程式語言一樣直覺,必須再加上關鍵字,如下: * 修改全域變數,必須在全域變數前面加關鍵字 `global`,不加關鍵字會報錯。 ```python= a = 10 def test(): global a # 一定要加 global 關鍵字 a = a + 1 print(a) test() ``` 或是透過傳參數修改: ```python= a = 10 def test(a): a = a + 1 print(a) test(a) ``` * 修改巢狀式內的 enclosing 作用域變數,必須在變數前面加上 `nonlocal` 關鍵字,不加關鍵字會報錯。 ```python= def outer(): num = 10 def inner(): nonlocal num # 一定要加 nonlocal 關鍵字 num = 100 print(num) inner() print(num) outer() ``` ## Ref. [Python3 命名空间和作用域](https://www.runoob.com/python3/python3-namespace-scope.html) ###### tags: `語法相關`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up