The function return value and a function of the variable scope

The function return value and a function of the variable scope

1. The return value of the function

Return Value : The result of calculation functions, requires further operations, a return value of the function to
return to return a function result, if the function does not return a value, the default return None
function upon return function execution encounters the end of the code behind not performed
when the plurality of the return value will help us python encapsulated into a tuple type

def mypow(x,y=2):
    return x**y,x+y  #返回x**y,x+y
    print('!!!!!')   #后面的代码不会执行
a = mypow(4)
print(a)             #多个返回值的时候 python会帮我们封装成一个元组类型

Output:
Here Insert Picture Description

2. The scope of variables

(1) local variables: internal variables can be referred to, i.e. variables inside a function definition, variables defined within the function only work inside the function variable is automatically deleted after the end of the function execution.
(2) global variables: either a function to create an object, it can be created anywhere in this program. Global variables can be referenced by all the objects of the present procedure or function.

a = 1                        # 全局变量
print('outside:', id(a))

def f():
    a = 5                    # 局部变量
    print('inside:', id(a))  # 局部变量在函数结束后被释放

f()
print(a)
print(id(a))

Output:
Here Insert Picture Descriptionglobal a: declare a global variable

a = 1
print('outside:', id(a))

def fun():
    global a                # 声明a为全局变量
    a = 5
    print('inside:', id(a))

fun()
print(a)
print(id(a))

Output:
Here Insert Picture Description

Published 60 original articles · won praise 6 · views 1359

Guess you like

Origin blog.csdn.net/weixin_45775963/article/details/103699238