一、局部变量与全局变量
name='lhf' 全局变量
def change_name():
global name 全局变量 不加global就是局部变量
name='帅了一比'
print('change_name',name)
change_name()
print(name)
name='lhf'
def change_name():
name1='帅了一比'
name2='帅了一比'
name3='帅了一比'
print('change_name',name)
globals关键字
NAME = "杠"
def yangjian():
global NAME
NAME = "小东北"
print('我要搞', NAME)
def qupengfei():
print('我要搞', NAME)
yangjian()
qupengfei()
--------------------------------------------------
NAME = "产品经理"
def yangjian():
# NAME = "史正文"
global NAME # 已经声明,NAME就是全局的的那个变量
print('我要搞', NAME)
NAME = "小东北" # 修改 全局的变量
print('我要搞', NAME)
def qupengfei():
NAME = "基"
print('我要搞', NAME)
如果函数的内容无global关键字,
- 有声明局部变量
NAME = ["产品经理","廖波湿"]
def qupengfei():
NAME = "自己"
print('我要搞', NAME)
qupengfei()
- 无声明局部变量
NAME = ["产品经理","廖波湿"]
def qupengfei():
NAME.append('XXOO')
print('我要搞', NAME)
qupengfei()
如果函数的内容有global关键字
- 有声明局部变量
NAME = ["产品经理","廖波湿"]
def qupengfei():
global NAME
NAME = "自己"
print('我要搞', NAME)
qupengfei()
错误示例
NAME = ["产品经理","廖波湿"]
def qupengfei():
NAME = "自己"
global NAME
print('我要搞', NAME)
qupengfei()
- 无声明局部变量
NAME = ["产品经理","廖波湿"]
def qupengfei():
global NAME
NAME = ["阿毛"]
NAME.append('XXOO')
print('我要搞', NAME)
qupengfei()
####### 全局变量变量名大写
####### 局部变量变量名小写
优先读取局部变量,能读取全局变量,无法对全局变量重新赋值 NAME=“fff”,但是对于可变类型,可以对内部元素进行操作
如果函数中有global关键字,变量本质上就是全局的那个变量,可读取可赋值 NAME=“fff”
NAME = '海风'
def huangwei():
name = "黄伟"
print(name)
def liuyang():
name = "刘洋"
print(name)
def nulige():
name = '沪指花'
print(name)
print(name)
nulige()
liuyang()
print(name)
huangwei()
name = "刚娘"
def weihou():
name = "陈卓"
def weiweihou():
nonlocal name # nonlocal,指定上一级变量,如果没有就继续往上直到找到为止
name = "冷静"
weiweihou()
print(name)
print(name)
weihou()
print(name)
二、前向引用
实例一:报错
def foo():
print('from foo')
bar()
foo()
实例2
def bar():
print('from bar')
def foo():
print('from foo')
bar()
foo()
实例3
def foo():
print('from foo')
bar()
def bar():
print('from bar')
foo()
实例4:报错
def foo():
print('from foo')
bar()
foo()
def bar():
print('from bar')
三、递归
1
def calc(n):
print(n)
if int(n / 2) == 0:
return n
res=calc(int(n / 2))
return res
2
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)