python學習-24 局部變量與全局變量

    局部變量與全局變量

 

1.沒有縮進的變量,爲全局變量函數

name = 'jphn'

在子程序裏定義的變量,局部變量spa

 

2.code

name = 'jphn'                    #全局變量


def a(): 
    name='andy'                    #局部變量
    print('a',name)
a()

運行結果:blog

a andy

Process finished with exit code 0

 

 

3.global 能夠修改全局變量it

不修改以前:class

name = 'jphn'


def a():
    name='andy'
    print('a',name)
a()

print(name)

運行結果:變量

a andy
jphn

Process finished with exit code 0

 

想要修改全局變量;引用

name = 'jphn'


def a():
    global name           #nonlocal 指定上一級變量, global指定全局變量
    name='andy'
    print('a',name)
a()

print(name)

運行結果:程序

a andy
andy

Process finished with exit code 0

 

 

4.嵌套di

name = '小明'                            

def a():
    name = '小紅'
    print(name)
    def b():
        name = '小剛'
        print(name)
        def c():
            name = '小王'
            print(name)
        print(name)
        c()
    b()
    print(name)
a()

運行結果:

小紅
小剛
小剛
小王
小紅

Process finished with exit code 0

 

5.前向引用

函數即變量

第一:

def bar():
    print('from bar')
def foo():
    print('from foo')
    bar()
foo()

運行結果:

from foo
from bar

Process finished with exit code 0

第二:

def foo():
    print('from foo')
    bar()
def bar():
    print('from bar')
foo()

運行結果:

from foo
from bar

Process finished with exit code 0
相關文章
相關標籤/搜索