python 局部變數和全域變數 day15

來源:互聯網
上載者:User

標籤:ext2   code   app   子程式   pen   end   oca   類型   pre   

全域變數,全域都可以調用的變數

局部變數,在子程式中可以調用的變數

name = ‘w‘def text():    name = ‘l‘    print(name)text()print(name)

global調用全域變數,且可以重新賦值,如果沒有則不能重新賦值

text()決定調用順序

name = ‘w‘def text():    global name    name = ‘l‘    print(name)def text2():    print(name)text2()text()print(name)

global調用全域變數,且可以重新賦值,如果沒有則不能重新賦值

name = ‘w‘def text():    global name    name = ‘l‘    print(name)def text2():    print(name)text()text2()print(name)

沒有global不能重新賦值,但對可變類型,可以對內部元素進行操作

name = [‘1‘,‘2‘]def a():    name.append(‘3‘)    print(name)a()print(name)

全域變數都大寫,局部變數都小寫

nonlocal指上一級變數

name = ‘w‘def abc():    name = ‘a‘    def bcd():        nonlocal name        name = ‘b‘    bcd()    print(name)print(name)abc()print(name)

 

python 局部變數和全域變數 day15

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.