python学习-24 局部变量与全局变量

时间:2019-07-03 17:19:00 来源:互联网 作者: 神秘的大神 字体:

    局部变量与全局变量

 

1.没有缩进的变量,为全局变量

name = 'jphn'

在子程序里定义的变量,局部变量

 

2.

name = 'jphn'                    #全局变量


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

运行结果:

a andy

Process finished with exit code 0

 

 

3.global 可以修改全局变量

不修改之前:

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.嵌套

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