Function Basic Knowledg

主要是做个笔记,以后可以方便梳理一下,尊重版权,特此申明下面信息均来自公司培训课PPT Nagiza F. Samatova, NC State Univ. All rights

Function ≡ Object
在这里插入图片描述
简单说,函数定义时用Parameters, 函数调用传入的实际内容就是Arguments
在这里插入图片描述
在这里插入图片描述
注意传入的arguments和函数parameters的顺序
在这里插入图片描述
作业,哈哈!能做对么?
在这里插入图片描述
Local变量和Global变量
在这里插入图片描述
Mutable 和 immutable 类型的变量的变化对global的影响是不一样的。
在这里插入图片描述
List是mutable类型,函数内local的变化会影响原本gloabal的变化

g_list = [1, 2, 3]
def scope_list(): 
    g_list [1] = 5
scope_list() 
print ( "\t Modified by function?  " + str(g_list))
# output: Modified by function?  [1, 5, 3]

immutable global 变量不能在函数中local改变
在这里插入图片描述
注意标红的部分,容易出错,global变化在函数中local处是可以读哈。
在这里插入图片描述
传入x[:]是x[]的一个copy,另外一个[]变量,跟原本的x[]是没有关系的,所以在函数中的parameter只是个local变量,不会影响到global变量x

x = [5]
def f(x):
    x[0] += 1
    
f(x[:])
print(str(x))  # output:[5]

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
no return

def format_name(first, last): 
    full_name = first.title() + ' ' + last.title() 
    
print(type(format_name ('nagiza', 'samatova')))
print(format_name ('nagiza', 'samatova'))
#output:
<class 'NoneType'>
None

return多个值,将多个值打包成tuple传出

def test(x):
    y1 = x+1
    y2 = x+2
    return y1,y2

result = test(2)
print(type(result)) #output:<class 'tuple'>
print(result) #output:(3, 4)

关于默认参数,将在下篇做深入研究,这很容易混淆。
在这里插入图片描述

在这里插入图片描述

def do_nothing():
    """the function that does nothing
    with zero input parameter
    and  zero return output values """
    pass

help(do_nothing)
Help on function do_nothing in module __main__:

do_nothing()
    the function that does nothing
    with zero input parameter
    and  zero return output values

猜你喜欢

转载自blog.csdn.net/wumingxiaoyao/article/details/108942536