来源:python中国网 时间:2019-09-07

  上节课我们知道了全局变量和局部变量的概念,也看到了全局变量可以在函数内直接输出。既然有全局变量和局部变量,那么全局变量和局部变量名字相同的时候会怎么样?函数内部是否可以修改全局变量?

  情况一:在函数内定义和全局变量同名的变量,则该变量为函数内的局部变量,和全局变量互不影响!

  情况二:如果是可变类型全局变量则函数内可以直接修改,如果是不可变类型全局变量则函数内部需要使用global声明才能更改。学习(可变和不可变类型)。

# -*- coding: utf-8 -*-

age = 18
ids = [1,2,3,4,5]

def test1():
    ids.append(2)
    print('test1函数我是ids',ids)

def test2():
    global age
    age = age + 1
    print('test2函数我是age',age)

def test3():
    age = age + 1
    print('test3函数我是age',age)

print('我是ids',ids)
test1()

print('我是age',age)
test2()

# 下面会报错
print('我是age',age)
test3()

D:python3installpython.exe D:/pyscript/py3script/python66/python66.py
Traceback (most recent call last):
我是ids [1, 2, 3, 4, 5]
  File "D:/pyscript/py3script/python66/python66.py", line 26, in 
test1函数我是ids [1, 2, 3, 4, 5, 2]
    test3()
我是age 18
test2函数我是age 19
  File "D:/pyscript/py3script/python66/python66.py", line 16, in test3
我是age 19
    age = age + 1
UnboundLocalError: local variable 'age' referenced before assignment

Process finished with exit code 1



  易错点,下面的问题有点深入,在函数中先修改全局变量再定义同名的局部变量。有兴趣的深入研究下。

# -*- coding: utf-8 -*-

age = 18
ids = [1,2,3,4,5]

def test1():
    ids.append(2)
    ids = [1]
    print('test1函数我是ids',ids)

test1()



D:python3installpython.exe D:/pyscript/py3script/python66/python66.py
Traceback (most recent call last):
  File "D:/pyscript/py3script/python66/python66.py", line 11, in 
    test1()
  File "D:/pyscript/py3script/python66/python66.py", line 7, in test1
    ids.append(2)
UnboundLocalError: local variable 'ids' referenced before assignment

Process finished with exit code 1