Python:变量在函数中的作用域

发布时间 2023-12-08 23:41:02作者: hugh2023

变量作用域指变量的作用范围(变量哪里可用,哪里不可用)

局部变量

定义在函数体内部的变量,即只在函数体内部生效

全局变量

定义在函数体内、外都能生效的变量

# 演示局部变量
# def test_a():
#     num = 100
#     print(num)
#
#
# test_a()
# print(num)


# 演示全局变量
num = 200

def test_b():
    print(f"test_b:{num}")


def test_c():
    print(f"test_c:{num}")


test_b()
test_c()
print(num)


# 在函数内修改全局变量
num = 300


def test_b():
    print(f"test_b:{num}")


def test_c():
    num = 500       # 局部变量
    print(f"test_c:{num}")


test_b()
test_c()
print(num)


# global关键字,可以在函数内声明变量为全局变量

num = 500


def test_b():
    print(f"test_b:{num}")


def test_c():
    global num      # 声明全局变量
    num = 600
    print(f"test_c:{num}")


test_b()
test_c()
print(num)