Python函数(三)-局部变量

  • 全局变量

全局变量在函数中能直接访问

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

name = 'John'

def test():
    print(name)

test()

运行结果

但是全局变量的值(数字,字符串)不会被函数修改

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

name = 'John'

def test(name):
    print("before change",name)
    name = 'Jack'
    print("after change",name)

test(name)
print(name)

运行结果

name变量在函数内被修改过,只在函数内有效,不影响全局变量的值,最后打印的全局变量的值还是不变

函数可以修改全局变量定义的列表,字典,集合

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

list_1 = ['Python','php','java']
dict_1 = {'name':'John','age':22}
set_1 = {'Chinese','Art','Math'}

def change():
    list_1[1] = 'asp'
    dict_1['name'] = 'Jack'
    set_1.pop() #随机删除一个值
    print(list_1)
    print(dict_1)
    print(set_1)

print(list_1)
print(dict_1)
print(set_1)
print("----------------+---------------")
change()
print("--------------After-Change--------------")
print(list_1)
print(dict_1)
print(set_1)

运行结果

全局变量里的列表,字典,集合都在函数内被修改了

  • 局部变量

局部变量就是在函数内定义的变量

直接定义一个局部变量

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

def test():
    name = 'John'
    print(name)

test()
print(name)

运行结果

函数内的局部变量函数外部访问不了,只能在函数内部调用

如果想让局部变量跟全局变量一样可以全局调用,需要用global关键字

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

def test():
    global name #把局部变量name设置为全局变量
    name = 'John'
    print(name)

test()
print(name)

运行结果

函数外也能访问到函数内定义的变量了

 

posted @ 2018-01-31 22:35  Sch01aR#  阅读(282)  评论(0编辑  收藏  举报