python | 浅学 | 10 global 与 nonlocal

total = 0  # 这是一个全局变量


# 可写函数说明
def sum(arg1, arg2):
    # 返回2个参数的和."
    total = arg1 + arg2  # total在这里是局部变量.
    print("函数内是局部变量 : ", total)
    return total


# 调用sum函数
sum(10, 20)
print("函数外是全局变量 : ", total)

num = 1
def fun1():
    global num  # 需要使用 global 关键字声明  当内部作用域想修改外部作用域的变量时,就要用到 global 和 nonlocal 关键字了。
    print(num)
    num = 123
    print(num)
fun1()
print(num)



def outer():
    num = 10
    def inner():
        nonlocal num   # 如果要修改嵌套作用域 nonlocal关键字声明
        num = 100
        print(num)
    inner()
    print(num)
outer()

# 如果没有global a时 test 函数中的 a 使用的是局部,未定义
a = 10
def test():
    global a
    a = a + 1
    print(a)
test()
#也可以通过函数参数传递
a = 10
def test(a):
    a = a + 1
    print(a)
test(a)

 

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...