python全局变量与局部变量的区别

全局变量与局部变量的区别在于作用域不同

全局变量适用于全局范围,在整个文件顶部声明的,可供文件中的任意函数调用

局部变量适用于局部范围,在函数体内定义使用的,只能在函数体内调用

1.函数内部调用全局变量

a="hello world!"

 

def fun():

    global a

    b=a

    return (("b="+b),("a="+a))

 

print (fun())

print ("a="+a)

运行结果:

('b=hello world!', 'a=hello world!')

a="hello world!"

2.函数内部使用与全局变量名相同的局部变量

a="hello world!"

def fun():

    a="hi"       #在函数体内重新定义a的值,不会对全局变量a重新赋值,为局部变量

    b=a

    return (("b="+b),("a="+a))

 

print (fun())

print (a)

运行结果为:

('函数体内b=hi', '函数体内a=hi')

函数体外a=hello world!

3.函数内修改全局变量

a="hello world!"

def fun():

    global a 

    a="hi"     #修改全局变量的值

    b=a

    return (("函数体内b="+b),("函数体内a="+a))

 

print (fun())

print ("函数体外a="+a)

运行结果为:

('函数体内b=hi', '函数体内a=hi')

函数体外a=hi

猜你喜欢

转载自blog.csdn.net/weixin_37579123/article/details/81112799