close

這算是各種語言都會碰到的一個問題:值域。

在python function 裡面一個變數在function 內跟外都會有不同的結果

可以用id(variable)來看看這個變數的id。

 

以下提供一個小測驗,使用方法:把下面的程式碼複製起來,放到你電腦裡測試。
在每一題的print(x)後面加上註解,預測你認為這會跑出什麼值。 最後實際跑跑看,看是不是跟你預期的相同。

 

x = 1
def test():
    x = 2
test()
print(x)


x = 1
def test():
    global x
    x = 2
test()
print(x)


x = [1]
def test():
    x = [2]
test()
print(x)


x = [1]
def test():
    global x
    x = [2]
test()
print(x)


x = [1]
def test():
    x[0] = 2
test()
print(x)

 

 

小測驗出處:

https://www.youtube.com/watch?v=xwPWcFKeIac&list=PLQVvvaa0QuDeAams7fkdcwOGBpGdHpXln&index=8

arrow
arrow
    全站熱搜

    工程師黑田 發表在 痞客邦 留言(0) 人氣()