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)直接调用了全局变量。

 

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值