forward reference前向引用,gloal values and local values全局变量和局部变量,recursive function递归函数

时间:2022-09-28 05:07:24

1.全局变量与局部变量练习

 1 # -*- coding: UTF-8 -*-
2 def bar():
3 print('from bar')
4 def foo():
5 print('from foo')
6 bar()
7 foo()
8
9 name = 'lhf'
10 def change_name():
11 global name
12 name = 'such a good young boy'
13 print('change_name',name)
14 def change_name1():
15 name1 = '帅了一比'
16 name2 = '帅了一比'
17 name3 = '帅了一比'
18 print('change_name',name)
19 change_name()
20 change_name1()
21 print(name)
22
23 NAME = '杠娘'
24 def yangjian():
25 global NAME
26 NAME = 'a cute little northwestern man'
27 print('i am going to hang out with ' + NAME)
28 def qupengfei():
29 NAME = 'alex'
30 print('i am going to hang out with ' + NAME)
31 yangjian()
32 qupengfei()
33
34 NAME = ['a','b']
35 def qupengfei():
36 NAME = 'myself'
37 print('i am fucking ' + NAME)
38 qupengfei()
39
40 NAME = ['c','d']
41 def yuyukun():
42 NAME.append('e')
43 print('i am fucking',NAME)
44 yuyukun()
45
46 result:
47 from foo
48 from bar
49 ('change_name', 'such a good young boy')
50 ('change_name', 'such a good young boy')
51 such a good young boy
52 i am going to hang out with a cute little northwestern man
53 i am going to hang out with alex
54 i am fucking myself
55 ('i am fucking', ['c', 'd', 'e'])
2.全局变量与局部变量 例子
#global keywork
name = '刚娘'
def weihou():
name = '陈卓'
def weiweihou():
global name #此处全局变量对应line780,表示重申变量name为全局变量
name = '冷静' #此处name仅为weiweihou()中的全局变量
weiweihou()
print(name) #此时打印的name对应'陈卓',因为weihou()中声明了name='陈卓'的局部变量
print(name)
weihou()
print(name)
#nonlocal keywork
name = '刚娘'
def weihou():
name = '陈卓'
def weiweihou():
nonlocal name #修改上级变量,陈卓改为冷静
name = '冷静'
weiweihou()
print(name)
print(name)
weihou()
print(name) result:
刚娘
陈卓
冷静 刚娘
冷静
刚娘

3.累加的递归练习

def add(n):
print(n)
if n == 1:
return n
else:
return (n + add(n-1))
res = add(10)
print(res) result:
10
9
8
7
6
5
4
3
2
1
55

4.公因子的递归练习

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

5.问路的递归练习

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(10)
res = ask_way(person_list)
print('%s问的结果是:%res'%(person,res))
return res
res = ask_way(person_list)
print(res)