python_day6

变量的作用域


'''
局部变量
    函数内定义的变量称为局部变量,在函数外不能使用

    在函数外定义的变量,函数内可以获取,但是不能更改

全局变量
    在函数内部使用global关键字定义的变量就是全局变量
    在函数外定义的变量,在函数内使用global关键字进行声明,那么也是全局变量


变量分两类
    可变数据类型:在函数外定义的变量,在函数内可以使用
        列表、字典
    不可变数据类型:在函数外定义的变量,在函数内可以访问,不能有其他操作

在函数外使用函数
globals() 获取全局数据
locals() 获取当前作用域数据
'''


num = 10

varlist = [1,2,3]
def func():

    # print(num)    #在函数内可以获取函数外部的变量
    # num += 20 #在函数内不能直接更改函数的外部变量
    #函数内定义的变量 局部变量
    love = 20
    love += 10
    print(love)

    print(varlist)
    varlist[2]='aa'

#     全局变量
    global live
    live = 'hello'

func()
print(live)
live = 'you'
print(live)
# print(love) # 函数内定义的变量,在函数外不能使用


print(globals())
print(locals())

# 问:为什么上面两个函数的结构一模一样
# 因为当前区域就是全局区域

# 不仅变量有作用域,函数一样也有相同的作用域

def outer():
    print('this is outer function...')
    # 在函数内定义的函数称为局部函数
    def inner():
        print('this is inner function...')

    inner()
outer()

nonlocal关键字以及函数文档

# 变量和函数都有作用域
# 在内函数中如何使用上一层函数中的局部变量

'''
在内函数中如果想使用外层函数的变量,那么需要使用 nonlocal 关键字 引用
'''


def outer():
    # 外函数的局部变量
    num = 10
    # 内函数,局部函数,在函数的内部定义的函数
    def inner():
        '''
        这里让你写当前函数的文档说明
        需要说明当前函数的作用
        如果当前函数还有形参,那么也需要对形参进一步一一说明
        :return: 此次说明...
        '''
        nonlocal num # 关键字在局部函数中使用,可以引用上一层函数中定义的局部变量,但依然不能提升为全局变量
        num += 1
        print(num)

    inner()
outer()


# 关于函数的文档
print(globals())
# print((inner.__doc__)) #获取当前函数的说明文档
'''
魔法变量
_name_ ==>当前脚本如果作为主程序,那么值_main_,如果当做一个模块,在另外一个脚本中引用去使用,那么值就是当前文件的名字
_doc_  ==>当前脚本的文档说明,在当前脚本当中的第一份,三引号就是当前脚本的说明文档



{ 
    '__name__': '__main__', 
    '__doc__': '\n在内函数中如果想使用外层函数的变量,
    那么需要使用 nonlocal 关键字 引用\n',
     '__package__': None, 
     '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000001A329E86D00>, 
     '__spec__': None,
      '__annotations__': {},
       '__builtins__': <module 'builtins' (built-in)>, 
       '__file__': 'D:\\金艳灵\\nonlocal关键字.py',
        '__cached__': None, 'outer': <function outer at 0x000001A32A36CB80>}

'''

函数封装的练习题

# 函数封装的练习题

# 打印九九乘法表,矩形,十二生肖

# 定义函数,打印九九乘法表
def jiujiu(n = 0):
    '''
        当前函数的功能:打印九九乘法表
        n = 0:n=0正向输出, n=1 反向输出
    :return:
    '''
    if n == 0:
        re = range(1,10)
    else:
        re = range(9,0,-1)
    for x in re:
        for y in range(1,x+1):
            print(f'{x}*{y}={x*y}',end=" ")
        print()

jiujiu(1)



# 封装打印矩形的函数
def juxing():
    for x in range(1,100):
        print(f'a ',end="")
        if x % 10 == 0:
            print ()

juxing()

递归函数

'''
递归函数:
    递归函数就是定义了一个函数,然后在函数内,自己调用了自己这个函数
    递归函数内必须要有接受,不然就会一直调用下去,直到调用的层数越来越多,栈溢出
    递归函数是一层层的进入再一层层的返回
    递归函数的效率并不高,尽量不使用就不使用
    一个函数如果调用后,没有结束,那么在栈空间就一直存在,直到这个函数运算结束才销毁

斐波那契数列
1 1 2 3 5 8 13
实现一个数的阶乘:
    1*2*3*4*5*6*7
'''

# 初步认识 递归函数 3 2 1 0
def digui(num):
    print(num)

    # 检测当前的值是否到了零
    if num > 0:
    # 调用函数本身
     digui(num-1)
     print(num) # 0 1 2 3
digui(3)

'''
解析当前递归函数的执行过程:
digui(3) ==> 3
    digui(3-1) ==> 2
        digui(2-1) ==> 1
            digui(1-1) ==> 0
            digui(0) ==> 0
        digui(1) ===> 1
    digui(2) ==> 2
digui(3) ==> 3
'''


# 实现递归函数——阶乘
# 求一个数的阶乘的结果 7 1*2*3*4*5*6*7
def jiecheng(n):
    if n == 1:
        return 1
    else:
        return n*jiecheng(n-1)

res = jiecheng(7)
print(res)

# 实现递归函数——斐波那契数列
def Fibonacci(pos):
    # check for the terminating condition
    if pos <= 1:
        # Return the value for position 1, here it is 0
        return 0
    if pos == 2:
        # return the value for position 2, here it is 1
        return 1

    # perform some operation with the arguments
    # Calculate the (n-1)th number by calling the function itself
    n_1 = Fibonacci(pos - 1)
    # calculation  the (n-2)th number by calling the function itself again
    n_2 = Fibonacci(pos - 2)
    # calculate the fibo number
    n = n_1 + n_2
    # return the fibo number
    return n


# Here we asking the function to calculate 5th Fibonacci
nth_fibo = Fibonacci(5)

print(nth_fibo)

回调函数

# 回调函数
# 如果在一个函数中要求传递的参数是一个函数作为参数,并且在函数中使用了传递进来的函数,那么这个函数我们称为是一个回调函数


# 定义一个函数,函数中的一个参数要求是另一个函数
# 带有回调函数参数的函数
def func(f):
    print(f,type(f))
#     并且在函数中调用了传递进来的形参函数
    f()

# 回调函数
def love():
    print('123')

func(love)

def func(x,y,z):
    '''
    当前函数接受两个数值,并把这两个数值传递给第三个参数进行运算
    x,y int
    z function
    :param x: int
    :param y: int
    :param z: int
    :return:  function
    '''
    print(f([x,y]))

print(sum([1,2]))

闭包函数

# 当一个函数的返回值是另外一个函数,而返回的那个函数如果调用了其父函数内部的其它变量,如果返回的这个函数在外部被执行,就产生了闭包
'''
闭包函数的特点:
    1.在外函数中定义了局部变量,并且在内部函数中使用了这个局部变量
    2.在外函数中返回内函数,返回的内函数就是闭包函数
    3.闭包函数主要在于保护了外函数中的局部变量,既可以被使用,又不会被迫坏
'''
money = 0
# 工作
def work():
    global money
    money += 100

# 加班
def overtime():
    global money
    money += 200

# 购物
def buy():
    global money
    money -= 100

# work()
# work()
# work()
# overtime()
# overtime()
# overtime()
# overtime()
# buy()
# buy()
# buy()
#
# 没钱了,被偷
# money = 0
# print(money)

def person():
    money = 0

    # 工作
    def work():
        nonlocal money
        money += 100

    # 加班
    def overtime:
        nonlocal money
        money += 200

    # 购物
    def buy():
        nonlocal money  # 在内函数中使用了外函数的临时变量
        money -=100
        print(money)
    # 在外函数中返回了内函数,这个内函数就是闭包函数
    return  work
res = person()
res()
res()
# 此时就不能够在全局中对money这个局部变量进行任何操作了
# 闭包的作用:保护了函数中的变量不受外部的影响,但是又能不影响使用


# 如何检测一个函数是否为闭包函数
# 函数名.__closure__如果是闭包函数返回cell
print(res.__closure__)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值