Python--函数--全局变量和局部变量
a=0 #函数外面的变量为全局变量
def hanshu():
a=2 #函数内部的变量为局部变量
print(a)
hanshu()
print(a)
a=[]
def hanshu():
a.append(1) #可修改全局变量
hanshu()
print(a)
a=3
def hanshu(): #def hanshu(a) 同样会报错
a=a+1 #局部变量没有声明,'='相当于赋值,一个新的变量,所以会报错
hanshu() #hanshu(a) 同样会报错
print(a)
局部变量找不到,去全局变量里找,去掉a=4后不报错
global:声明为全局变量
a=3
def hanshu():
global a #声明为全局变量
a=5 #重新赋值,全局变量的值改变
print(a)
hanshu()
print(a)
nonlocal,外部变量(非全局变量)
def hanshu():
a=30
def neibu():
nonlocal a #外部变量(非全局变量)
a=40
print(a) #未调用函数,值为30
neibu()
print(a) #调用函数后,值为40
hanshu()
变量的查找顺序 从里向外查找
LEGB
L–LOCAL 局部作用域
E–ENCLOAE 嵌套作用域
G–GLOBAL 全局
B–BUILT-IN 内置
例:
a=100
c=1
b=30
def waibu():
b=200
c=2
def neibu():
c=300
print(c) #LOCAL
print(b) #ENLCOSE
print(a) #GLOBAL
print(max) #BUILT-IN
neibu()
waibu()
求斐波那契数列
def fbnq(n):
if n==1 or n==2:
return 1
else:
return fbnq(n-1)+fbnq(n-2)
for i in range(1,13):
print('第%d个月的兔子数量是:'%i,fbnq(i))