函数的返回值和1作用域

函数的返回值和1作用域

#_author:Administrator
#date:2019/11/1
# 小结
# 1.变量查找顺序:LEGB
# 2.只有模块,类,及函数才能引入新作用域
# 3.对于一个变量,内部作用域先声明就会覆盖外部变量。不声明直接使用,就会使用外部作用域的变量
# 4.内部作用域要修改外部作用域变量的值时,全局变量要使用global关键字,嵌套作用域变量要使用nonlocal

#1函数的返回值
#作用:(1)结束函数
# (2)返回某个对象
#Notice:
#1.函数里如果没有return,会默认返回一个None
#2.如果return多个对象,那么python会帮我们将多个对象封装成一个元组返回

def add(*args):
Sum = 0
for i in args:
Sum+=i
print(Sum)

a=add(1,2,3)#6
print(a)#None
def info():
return 1,'star',[1,2,3]
b=info()
print(b)#(1, 'star', [1, 2, 3])
print('-----------------------------')
#2.函数作用域
#python中的作用域分四种情况
#built-in ---> global --> enclosing --> local(从外到内)
x=int(3.3) #built-in
g_count=0 #global
def outer():
o_count=1 #enclosing
def inner():
i_count=2 #local
print(i_count)
#print(i_count) 找不到
inner()
outer()

print('------------------')
count1=10
def outer1():
global count1 #global对全局变量做修改用的
print(count1)#10
count1=5
print(count1)#5
outer1()
print('------------------')
def outer2():
count2=10
def inner2():
nonlocal count2 #nonlocal 对 enclosing变量做修改用的
count2=20
print(count2)#20
inner2()
print(count2)#20
outer2()

原文地址:https://www.cnblogs.com/startl/p/11777659.html