簡體   English   中英

show() function 給了我 15 我明白但是為什么 print(x) function 返回 13 我不明白我是 Z23EEEB4347BDD26BFC6B7EE9A3B755DDs 的新手

[英]the show() function gives me 15 & I understand but why does the print(x) function return 13 I don't get it I am new to python can you pls help me

我試圖了解python 中的全局變量和局部變量,並嘗試了下面提到的代碼,但由於某種原因, show()語句運行良好,我理解這一點,但 show() 下面的print(x)語句打印13而我期待它打印15

 def show():
        x=10
        x+=5
        print(x)

    show()
    
    print(x)

function 之外的打印語句根本不應該工作。 如果您在 function 內部定義變量,則不能在其外部調用它。

此外,如果您的代碼如下所示:

x = 13

def show():
    x = 10
    x += 5
    print(x)

show()

print(x)

第二個打印語句仍將返回 13,因為通過寫入x = 10 ,您正在 function 中創建一個名為 x 的新變量,在此 function 之外將無法訪問該變量。

x 可能在 function 之前定義 盡量不要多次使用相同的變量名

假設 x 在此之前沒有定義,這段代碼應該可以工作

def show():
  x = 10
  x += 5
  return x
show()
print(x)

暫無
暫無

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

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