好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解Python函数的使用

1.函数的基本定义

def 函数名称(参数)
         执行语        
         return 返回值 
def fun_ex(a,b):            #a,b是函数fun_ex的形式参数,也叫形参
    sum=a+b    print('sum =',sum)
fun_ex(1,3)                  #1,3是函数fun_ex的实际参数,也叫实参#运行结果sum = 4 
def fun_ex(a,b=6):    #默认参数放在参数列表最后,如b=6只能在a后面
    sum=a+b    print('sum =',sum)
fun_ex(1,3)
fun_ex(1)#运行结果sum = 4sum = 7 

4.函数的动态参数

不需要指定参数是元组或字典,函数自动把它转换成元组或字典,如:

#转换成元组的动态参数形式,接受的参数需要是可以转成元组的形式,就是类元组形式的数据,如数值,列表,元组。

def func(*args):
    print(args,type(args))

func(1,2,3,4,5)

date_ex1=('a','b','c','d')
func(*date_ex1)

#运行结果
(1, 2, 3, 4, 5) <class 'tuple'>
('a', 'b', 'c', 'd') <class 'tuple'>

动态参数形式一 
#转换成字典的动态参数形式,接收的参数要是能转换成字典形式的,就是类字典形式的数据,如键值对,字典

def func(**kwargs):
    print(kwargs,type(kwargs))

func(a=11,b=22)

date_ex2={'a':111,'b':222}
func(**date_ex2)

#运行结果
{'b': 22, 'a': 11} <class 'dict'>
{'b': 222, 'a': 111} <class 'dict'>

动态参数形式二 
#根据传的参数转换成元组和字典的动态参数形式,接收的参数可以是任何形式。
def func(*args,**kwargs):
    print(args, type(args))
    print(kwargs,type(kwargs))

func(123,321,a=999,b=666)

date_ex3={'a':123,'b':321}
func(**date_ex3)

#运行结果
(123, 321) <class 'tuple'>
{'b': 666, 'a': 999} <class 'dict'>
() <class 'tuple'>
{'b': 321, 'a': 123} <class 'dict'>

动态参数形式三 

5.函数的返回值

运行一个函数,一般都需要从中得到某个信息,这时就需要使用return来获取返回值,如:

def fun_ex(a,b):
    sum=a+b
    return sum      #返回sum值

re=fun_ex(1,3)   
print('sum =',re)

#运行结果
sum = 4 

6.lambda表达式

用来表达简单的函数,如:

#普通方法定义函数
def sum(a,b):
    return a+b
sum=sum(1,2)
print(sum)

#lambda表达式定义函数
myLambda = lambda a,b : a+b
sum=myLambda(2,3)
print(sum)

#运行结果
5 


7.内置函数

1)内置函数列表

Built-in Functions abs() dict() help() min() setattr() all() dir() hex() next() slice() any() pmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod() bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray() filter() issubclass() pow() super() bytes() float() iter() print() tuple() callable() format() len() property() type() chr() frozenset() list() range() vars() classmethod() getattr() locals() repr() zip() compile() globals() map() reversed() __import__() complex() hasattr() max() round() delattr() hash() memoryview() set()

以上就是详解Python函数的使用 的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于详解Python函数的使用的详细内容...

  阅读:41次