Python函数基础

函数是将程序中的一段通用代码封装起来,起个名字,程序的其他地方可以方便的调用

函数的定义

def  函数名(参数1,参数2...)

     do something...

    return 值/对象、函数等

#coding:gbk

def python_class(n):
    print("周六有%s位学习Python" % n)
    return True

python_class(20)

参数类型

1:普通
2:默认参数
3:可变长参数
 
#coding:gbk

def test_args(a,b=1):
    print(a,b)
    print(a+b)
    
test_args(3)
test_args(3,2)

可变长参数 调用函数的时候,可以传入任意形式任意个数的参数。

*  代表元祖,会把所有没有指定key的参数,把这一类参数放到一个元组中去。

** 代表的是字典  会把所有指定key的参数,放到字典当中。

*args  :    tuple

**kwargs :  就是当你传入key=value是存储的字典

#coding:gbk

def test_args(*args,**kwargs):
    print(args,kwargs)
    
test_args(3,5,a=1,b=2)

函数的返回值

#coding:gbk

def test(m,n):
    return m,n

print(test(1,2A))

原文地址:https://www.cnblogs.com/hellojackyleon/p/9102407.html