【全局变量和局部变量】
1、在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量。
全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序。
2、当全局变量与局部变量同名时:
在定义局部变量的子程序内,局部变量起作用;在其它地方全局变量起作用。
一个例子:
name = 'yxy'
def change_name():
name = 'alex'
print(name)
change_name() #alex
print(name) #yxy
【在子程序内修改全局变量】
name = 'yxy'
def change_name():
global name #本质是:在这个子程序中没有创建变量,用的是全局的变量。global是用来申明引用的是全局变量
name = 'alex'
print(name)
change_name() #alex
print(name) #alex
注意:代码从上到下执行,遇到def先创建”箱子“,但是“箱子”里的内容先不执行,如果下文调用了def,再执行“箱子”内部的代码。
注意:如果函数的内容无global关键字,优先读取局部变量,如果没有局部变量再读取全局变量,不能给全局变量重新赋值(但是,可以对可变对象进行内部元素操作);如果函数中有global关键字,变量本质上就是那个全局变量,可以读取和重新赋值。(以下是每种情况的例子)
example1:
--------------有申明同名局部变量时--------------
name = ['a','b']
def test():
name = 'c'
print(name)
test() #c
--------------没有申明同名局部变量时--------------
name = ['a','b']
def test():
name.append('c') #可以修改可变类型内部的元素
print(name)
test() #['a', 'b', 'c']
example2:
------------函数中有global关键字但没有局部变量时------------
name = ['a','b']
def test():
global name
name = 'c'
print(name)
test() #c
print(name) #c
------------函数中有global关键字但没有局部变量时------------
name = ['a','b']
def test():
global name
print(name)
test() #['a', 'b']
【函数的嵌套】
example:
name = 'a'
def test01():
name = 'b'
def test02():
global name
name = 'c'
test02()
print(name)
print(name)
test01()
print(name)
#a
#b
#c
【nonlocal:找上一级变量】
name = 'a'
def test01():
name = 'b'
def test02():
nonlocal name
name = 'c'
test02()
print(name)
print(name)
test01()
print(name)
#a
#c
#a
【风湿理论:函数即变量(前向引用)】
【函数递归】
以下两个例子来自:
example1:
def calc(n):
print(n)
if int(n/2) ==0:
return n
return calc(int(n/2))
res = calc(10)
print(res)
#输出:
#10
#5
#2
#1
#1
example2:
import time
person_list=['alex','wupeiqi','yuanhao','linhaifeng']
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(3)
res=ask_way(person_list)
# print('%s问的结果是: %res' %(person,res))
return res
res=ask_way(person_list)
print(res)
输出为:
------------------------------------------------------------
hi 美男[alex],敢问路在何方
alex回答道:我不知道,但念你慧眼识猪,你等着,我帮你问问['wupeiqi', 'yuanhao', 'linhaifeng']...
------------------------------------------------------------
hi 美男[wupeiqi],敢问路在何方
wupeiqi回答道:我不知道,但念你慧眼识猪,你等着,我帮你问问['yuanhao', 'linhaifeng']...
------------------------------------------------------------
hi 美男[yuanhao],敢问路在何方
yuanhao回答道:我不知道,但念你慧眼识猪,你等着,我帮你问问['linhaifeng']...
------------------------------------------------------------
linhaifeng说:我知道,老男孩就在沙河汇德商厦,下地铁就是
递归特性:
1. 必须有一个明确的结束条件
2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少
3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)