[課程討論] Day 12 - Beginner - Scope & Number Guessing Game

Py基礎組,已於2021/4/25 PM 9:00,進行Day 12課程討論。
相關資訊,更新於此

1個讚

Questions.

  1. Scope & Variable look-up: LEGB
  2. return代表程式結束?return vs pass?
  3. import, function, variable, and logic, which comes first?

Python Scope & the LEGB Rule: Resolving Names in Your Code

In Python, what is the difference between pass and return

Is there a difference between continue and pass in a for loop in python?

Imports

Python 的 Import 陷阱
https://medium.com/pyladies-taiwan/python-的-import-陷阱-3538e74f57e3

qnjej0u6cvxdivuq85fw

在Python Taiwan上,看到的問題。我也是不懂為什麼,會是錯誤?
Google了一下,貼在這邊,當作紀錄。

a = 11

def test():
    print(a)
    a = 21

test()
UnboundLocalError: local variable 'a' referenced before assignment

[Day 14] 楚河漢界劃清楚!

我的理解是:
在 test() 函數中,如果你想改變 global 變數( a=11),就必須在 test()中先宣告為 global。

def test():
    global a
    print(a)
    a = 21

如果不想改變,那麼 a 在 test() 中就是 local 變數,a 就必須在 print(a) 之前宣告。

def test():
    a = 21
    print(a)

不先宣告的話,就會有那個錯誤訊息 local variable ‘a’ referenced before assignment。
有錯的話,煩請指正。

2個讚