Python之全局变量和局部变量

1. 全局变量与局部变量:

name = 'test'    -- 全局变量
def test():
    name = 123   -- 局部变量
    print(name)
test()
print(name)
结果:
123
test

name = 'test'
def test():
    global name  当调用test函数时,会将name定义为全局变量
    name = 123
    print(name)
test()
print(name)
结果:
123
123

2. 如果函数的内部没有global关键字,优先读取局部变量;且只能读取全局变量(不严谨),不能进行重新赋值

  但对与可变类型,可以对内部元素进行操作

name = ['test','123']
def test():
    name.append('hello')
    print(name)
test()
print(name)
结果:
['test', '123', 'hello']
['test', '123', 'hello']

3. 如果函数中带有global关键字,变量本质上就是全局的那个变量,可以读取,可以进行赋值

变量命名规则:
    1. 全局变量名大写
    2. 局部变量名小写

 

 

 

 

 

  

posted @ 2020-10-23 22:59  九霄风云  Views(30)  Comments(0)    收藏  举报