zoukankan      html  css  js  c++  java
  • 第八天——函数的嵌套以及gloabal、nonlocal(三)(重点:执行过程)


    函数的嵌套以及gloabal、nonlocal

    一. 函数的嵌套

    1. 只要遇见了()就是函数的调用. 如果没有()就不是函数的调用
    2. 函数的执行顺序
    def fun1():   
        print(111)  
    def fun2():   
        print(222)   
        fun1()   
    fun2()
    print(111)
    

    def fun2():   
        print(222)   
        def fun3():       
            print(666)   
        print(444)   
        fun3()   
        print(888)
    print(33)
    fun2()
    print(555)
    

    在这里插入图片描述

    一:函数的调用:

    • 加()代表调用函数,当在续航徐中发现通过函数名加(),就会找到函数的定义代码,依次向下执行;
    • return 函数的返回值: 遇到return,此函数结束,return下面的代码不执行;
      其中如果return后面什么都不写,或者干脆不写return,返回的结果为None,果果return后面有值,则返回该值;
      return在哪里调用,就返回哪里,且谁调用就返回给谁;

    二:函数的嵌套以及执行流程:

    实例1:
    在这里插入代码片
    结果为:1
    实例2:
    在这里插入图片描述
    结果:2

    实例3:
    在这里插入图片描述
    结果为:None

    实例4:
    在这里插入图片描述

    实例5:
    在这里插入图片描述
    结果:None

    实例6:
    在这里插入图片描述
    结果:123 5

    二 .gloabal、nonlocal

    首先我们写这样一个代码, 首先在全局声明一个变量, 然后再局部调用这个变量, 并改变这 个变量的值

    a = 100
    def func():   
        global a    # 加了个global表示不再局部创建这个变量了. 而是直接使用全局的a   
        a = 28   
    print(a)
    func()
    print(a)
    

    global表示. 不再使用局部作用域中的内容了. 而改用全局作用域中的变量

    2.1global 宗旨

    在函数内部修改全局的变量,如果全局中不存在就创建一个变量

    lst = ["麻花藤", "刘嘉玲", "詹姆斯"]
    def func():   
        lst.append("⻢云")   
        # 对于可变数据类型可以直接进⾏访问
       print(lst)
    func()
    print(lst)
    

    2.2 nonlocal宗旨

    nonlocal 只修改上一层变量,如果上一层中没有变量就往上找一层,只会找到函数的最外层,不会找到全局进行修改

    a = 10
    def func1():   
        a = 20   
        def func2():
            nonlocal a       
            a = 30       
            print(a)  
        func2()   
        print(a)
    func1()
    
    
    结果:
    加了nonlocal
    30
    30
    
    不加nonlocal
    30
    20
    

    再看, 如果嵌套了很多层, 会是一种什么效果:

    a = 1
    def fun_1():   
        a = 2   
        def fun_2():       
            nonlocal a       
            a = 3       
            def fun_3():           
                a = 4           
                print(a)       
            print(a)       
            fun_3()       
            print(a)   
        print(a)   
        fun_2()   
        print(a)
    print(a)
    fun_1()
    print(a)
    

    这样的程序如果能分析明白. 那么作用域, global, nonlocal就没问题了

    有志者,事竟成,破釜沉舟,百二秦关终属楚; 苦心人,天不负,卧薪尝胆,三千越甲可吞吴。 想到与得到中间还有两个字——做到。
  • 相关阅读:
    SVN服务器搭建(一)
    排序算法二:冒泡排序
    【LeetCode】136. Single Number
    【LeetCode】217. Contains Duplicate
    【LeetCode】189. Rotate Array
    【LeetCode】122. Best Time to Buy and Sell Stock II
    【LeetCode】26. Remove Duplicates from Sorted Array
    【LeetCode】20. Valid Parentheses
    【LeetCode】680. Valid Palindrome II
    【LeetCode】345. Reverse Vowels of a String
  • 原文地址:https://www.cnblogs.com/huoxc/p/13064830.html
Copyright © 2011-2022 走看看