第四天 函数递归

局部变量 全局变量

全局变量:在整个文件里生效,在任何位置都能使用
局部变量:只能在局部使用
    name = '123'
    def test():
        name ='dfsaf'
        print(name)    #调用现在局部找  找不到才去外面找全局变量
    test()

    print(name)
    dfsaf
    123
    #若要在函数里面修改全局变量 要进行一个申明 global name  #地址引用 指针 
        name = '123'
    def test():
        global name
        name ='dfsaf'
        print(name)
    test()
#无global 
    有声明变量 局部变量优先调用
    无声明变量 调用全局变量 对于可变类型 可以对内部元素进行操作
        如 name.append()
        
        
#有global
    有声明变量 global 要放在开头
    无同名的变量 调用全局变量
    
#函数的嵌套:
例1    def test():
        name = 'dfsaf'
        print(name)
        def abv():
            name1 = 123
            print(name1)
        abv()
    test()
    >>>
    'dfsaf'
    123
例2    name = '刚娘'
    def test():
    name = '陈卓'
    def abv():
        global name
        name  = 123
    abv()
    print(name)
    test()
    >>>陈卓
    
###指向上一级变量 nonlocal


##########前向引用
1、    def too():
        print('fa')
        bar()
    def bar():
        print('fas')
    too()
###########风湿理论:函数即变量
                                函数在定义时python将定义以字符串的形式存储到内存

#############递归  相当于循环
递归特性
    1、要有终止条件

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


例2
person_list = ['alex','wupeiqi','linhaifeng','zsc']
import time
def ask_way(person_list):
    if len(person_list)==0:
        return '没人知道'
    person = person_list.pop(0)
    if person =='linhaifeng':
        return '%s说:我知道路在哪,文东路10号' %person
    print('你好%s,请问路在哪里?'%person)
    print('{}回答说:我不知道,我帮你问问{}'.format (person,person_list))
    time.sleep(0)
    res = ask_way(person_list)
    return res
res = ask_way(person_list)
print(res)

 

posted @ 2018-02-13 09:16  MrZY  阅读(114)  评论(0编辑  收藏  举报