day15_函数基础

一,局部变量和全局变量

全局变量:在所有函数外部定义的变量称为全局变量(Global Variable),它的作用域默认是整个程序。

1 顶头写的没有任何缩进
2 全局变量在任何位置都能调用
3 全局变量定义必须在所有函数之外
4 全局变量可加强函数模块之间的数据联系,但是函数又依赖这些变量,降低函数的独立性。
5 在同一源文件中,允许全局变量和局部变量同名,在局部变量作用域内,同名的全局变量不起作用。

局部变量:函数内部的变量称为局部变量(Local Variable),它的作用域仅限于函数内部, 离开该函数后就是无效的,再使用就会报错。

1 主函数中定义的变量也只能在主函数中使用,不能在其他函数中使用。
2 允许在不同的函数中使用相同的变量名,他们代表不同变量,分配不同的存放单元,互不相干,不会发生混淆。
3 复合语句中定义的变量,只限于使用当前函数中,也是复合语句的局部变量,复合语句:就是用{}包含起来的语句块。
4 形参变量、在函数体内定义的变量都是局部变量。实参给形参传值的过程也就是给局部变量赋值的过程。

如果函数中的内容无global关键字

- 有申明局部变量

name = "liyang"
def change_name():
    name = 'sun'
    print('name',name)
change_name()
print(name)

输出结果:
name sun
liyang

- 无申明局部变量

name = ["liyang","sun"]
def change_name():
    name.append("lili")
    print('name',name)
change_name()
输出结果:
name ['liyang', 'sun', 'lili']

如果函数的内容有global关键字:

- 有声明局部变量

NAME = ["liyang","sun"]
def change_name():
    global NAME
    NAME = "lili"
    print('name',NAME)
change_name()
输出结果:
name lili

- 无声明局部变量

NAME = ["liyang","sun"]
def change_name():
    global NAME
    NAME = ["lili"]
    NAME.append("xiaoz")
    print('name',NAME)
change_name()
name ['lili', 'xiaoz']

ps:修改全局变量

1 global 定义name为全局变量,意味着往下调用的name都是这个变量。
2 如果函数的内容中无global关键字,优先读取局部变量,能读取全局变量,无法对全局变量重新赋值 NAME='fff',但是对于可变类型,可以对内部元素进行操作。
3 如果函数中有global关键字,变量本质上就是全局的那个变量,可读取可修改。

二,函数

嵌套函数

NAME = 'sun'
def liyang():
    name = "李阳"
    print(name)
    def sunny():
        name = "sunny"
        print(name)
        def lili():
            name = "李利"
            print(name)
        print(name)
        lili()
    sunny()
    print(name)
liyang()
输出结果:
李阳
sunny
sunny
李利
李阳

global 关键字

name = "sun"
def test01():
    name = "李阳"
    def test02():
        global name
        name = "sunny"
    test02()
    print(name)
print(name)
test01()
print(name)
sun
李阳
sunny

nonlocal 关键字,指定上一级变量

name = "sun"
def test01():
    name = "李阳"
    def test02():
        nonlocal name
        name = "sunny"
    test02()
    print(name)
print(name)
test01()
print(name)

输出结果:
sun
sunny

前向引用之“函数即变量”

def bar():
    print('from bar')
    bar()

def foo():
    print('from foo')
foo()
输入结果:
from foo

递归(调用自己)

实例1:

def calc(n):
    print(n)
    if int(n/2) == 0:
        return n
    res = calc(int(n/2))
    return  res
calc(10)

实例2:

import time
person_list = ["liyang","sun","lili"]

def ask_way(person_list):
    if len(person_list) == 0:
        return 'xxxxx'
    person = person_list.pop(0)
    if person == "sun":
        return '%s说: 我知道!' %person
    time.sleep(3)
    res = ask_way(person_list)
    return res
res = ask_way(person_list)
print(res)

 

posted on 2018-05-03 21:14  sun_man  阅读(251)  评论(0编辑  收藏  举报