局部变量与全局变量

全局变量

  • 在python脚本最上层代码块的变量
  • 全局变量可以在函数内被读取使用

局部变量

  • 在函数体内定义的变量
  • 局部变量无法在自身函数以外使用

global

  • 将全局变量可以在函数体内进行修改

    1. 定义一个全局变量

    2. 定义函数

      global + 全局变量名

    3. 函数体内给全局变量重新赋值

  • 工作中, 不建议使用global全局变量进行修改

  • 仅支持 数字 字符串 空类型 布尔类型 的声明

  • 列表和字典的全局变量不需要global进行声明

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# coding:utf-8

name = 'dewei'
age = 33


def test():
print(name)


test()


def test1():
name = '小慕'
print('函数体内', name)


test1()
print('函数体外', name)


def test3():
age = 33
print(age)


test3()
# print(age)


def test4(a):
a = 10


test4(name)
print(name)


def test5():
global name
global age
name = 10
age = 10

test5()
print(name)
print(age)


test_dict = {'a': 1, 'b': 2}


def test6():
test_dict['c'] = 3
test_dict.pop('a')


test6()
print(test_dict)