【13】Python学习笔记:局部变量与全局变量,函数递归,前向引用

局部变量与全局变量

name='海风'
def huangwei():
    name = "黄伟"
    print(name)
    def liuyang():
        name = "刘洋"
        print(name)
        def nulige():
            name = '炉指花'
            print(name)
        print(name)
        nulige()
    liuyang()
    print(name)

print(name)
huangwei()
print(name)

得到输出结果:

海风
黄伟
刘洋
刘洋
炉指花
黄伟
海风

 

函数递归(问路小程序)

import time

person_list=['alex','wupeiqi','linhaifeng','zsc']

def ask_way(person_list):
    print('-'*60)
    if len(person_list) == 0:
        return '根本没人知道'
    person=person_list.pop(0)
    if person == 'linhaifeng':
        return '%s说:我知道,老男孩就在沙河汇德商厦,下地铁就是' %person

    print('hi 美男[%s],敢问路在何方' % person)
    print('%s回答道:我不知道,但念你慧眼识猪,你等着,我帮你问问%s...' % (person, person_list))
    time.sleep(1)
    res=ask_way(person_list)

    print('%s问的结果是: %res' %(person,res))
    return res

res=ask_way(person_list)
print(res)

得到输出结果:

------------------------------------------------------------
hi 美男[alex],敢问路在何方
alex回答道:我不知道,但念你慧眼识猪,你等着,我帮你问问['wupeiqi', 'linhaifeng', 'zsc']...
------------------------------------------------------------
hi 美男[wupeiqi],敢问路在何方
wupeiqi回答道:我不知道,但念你慧眼识猪,你等着,我帮你问问['linhaifeng', 'zsc']...
------------------------------------------------------------
wupeiqi问的结果是: 'linhaifeng说:我知道,老男孩就在沙河汇德商厦,下地铁就是'es
alex问的结果是: 'linhaifeng说:我知道,老男孩就在沙河汇德商厦,下地铁就是'es
linhaifeng说:我知道,老男孩就在沙河汇德商厦,下地铁就是

前向引用

在Python中不允许前向引用,即在函数定义之前,不允许调用该函数。如:

print(add(1,2))

def add(a,b):
    return a+b

得到输出结果:

  File "C:/Users/CALL_ME_K/PycharmProjects/Python_FullStack/day15/day15_s1.py", line 45, in <module>
    print(add(1,2))
NameError: name 'add' is not defined

猜你喜欢

转载自blog.csdn.net/CALL_ME_K/article/details/81662412