Python函数-局部变量

Posted Sch01aR#

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)

运行结果

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

 

以上是关于Python函数-局部变量的主要内容,如果未能解决你的问题,请参考以下文章

Python全栈之路----函数----局部变量

PYTHON 函数局部变量和全局变量

Python20之全局变量和局部变量

python3--函数(函数,全局变量和局部变量,递归函数)

自动化测试时需要使用python,请问如何理解python中的全局变量和局部变量?

python函数(全局变量,局部变量,作用域,递归函数,高阶函数,匿名函数)