Python 学习笔记——函数中的局部变量和全局变量

  1. 局部变量是函数内部的占位符,与全局变量可能重名但不同(当变量为基本数据类型时)。
  2. 函数定义或调用结束后,局部变量将被释放(不再存在),在函数外部调用局部变量将出错(变量未定义)。
  3. 在函数内使用global保留字可使用全局变量。
  4. 当局部变量为组合数据类型且未创建,等同于全局变量。

举例如下:

代码1:

def createList(a, b):
    numbers = []
    i = 0
    while i < a:
        print(f"At the top i is {i}")
        numbers.append(i)

        i = i + b
        print("Numbers now: ", numbers)
        print(f"At the bottom i is {i}")

createList(8, 2)

print("The numbers: ")

for num in numbers:
    print(num)

 运行结果:

At the bottom i is 4
At the top i is 4
Numbers now:  [0, 2, 4]
At the bottom i is 6
At the top i is 6
Numbers now:  [0, 2, 4, 6]
At the bottom i is 8
The numbers: 


numbers未定义,因此for循环的输出为空 。

代码2:

numbers = []

def createList(a, b):
    i = 0
    while i < a:
        print(f"At the top i is {i}")
        numbers.append(i)

        i = i + b
        print("Numbers now: ", numbers)
        print(f"At the bottom i is {i}")

createList(8, 2)

print("The numbers: ")

for num in numbers:
    print(num)

运行结果:

At the top i is 0
Numbers now:  [0]
At the bottom i is 2
At the top i is 2
Numbers now:  [0, 2]
At the bottom i is 4
At the top i is 4
Numbers now:  [0, 2, 4]
At the bottom i is 6
At the top i is 6
Numbers now:  [0, 2, 4, 6]
At the bottom i is 8
The numbers: 
0
2
4
6

可以看到,函数内部未定义numbers变量,numbers.append(i)直接调用了全局变量。

 

posted @ 2018-08-04 17:31  kaka4NERV  阅读(400)  评论(0)    收藏  举报