簡體   English   中英

更新變量

[英]Updation of the variable

def fun(x):
    x += 1
    return x

x = 2
x = fun(x + 1)
print(x)

據說在 function 之外聲明的變量,在 function 中不能寫入但可以讀取,除非變量聲明為global ,那么這里如何更新 x 的值?

def fun(x):
    x += 1                  => Adds 1 to the x from the method argument
    return x                => Returns the new value of x

x = 2                      
x = fun(x + 1)              => Call the function as fun(2 +1) which returns 3 + 1 and assigns to the variable x
print(x)                    => Prints the latest x value which is 4.

為了進一步澄清,讓程序稍微改變一點,而不影響程序的結果:

def fun(y):
    y += 1
    return y

x = 2
x = fun(x + 1)
print(x)

這里,function 內部使用的變量與調用 function 的變量完全不同。

因此,x 的值被更新只是因為函數返回了 x 的更新值,然后將 x = func(x) 分配給 x,它與變量名無關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM