首页 > 编程语言 > 详细

Python 函数

时间:2017-03-23 02:44:15      阅读:246      评论:0      收藏:0      [点我收藏+]

1.函数的基本定义

def 函数名称(参数):
         函数体
def 函数名称(参数)
         执行语句
         return()
def 函数名称(参数)
         执行语句
         return 返回值

def : 定义函数的关键字;

函数名称:顾名思义,就是函数的名字,可以用来调用函数,不能使用关键字来命名,做好是用这个函数的功能的英文名命名,可以采用驼峰法与下划线法;

参数:用来给函数提供数据,有形参和实参的区分;

执行语句:也叫函数体,用来进行一系列的逻辑运算;

返回值:执行完函数后,返回给调用者的数据,默认为None,所以没有返回值时,可以不写return。

 

2.函数的普通参数

最直接的一对一关系的参数,如:

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

 

3.函数的默认参数

给参数定义一个默认值,如果调用函数时,没有给指定参数,则函数使用默认参数,默认参数需要放在参数列表的最后,如:

def fun_ex(a,b=6):    #默认参数放在参数列表最后,如b=6只能在a后面
    sum=a+b
    print(sum =,sum)
fun_ex(1,3)
fun_ex(1)

#运行结果
sum = 4
sum = 7

 

4.函数的动态参数

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

技术分享
 1 #转换成元组的动态参数形式,接受的参数需要是可以转成元组的形式,就是类元组形式的数据,如数值,列表,元组。
 2 
 3 def func(*args):
 4     print(args,type(args))
 5 
 6 func(1,2,3,4,5)
 7 
 8 date_ex1=(a,b,c,d)
 9 func(*date_ex1)
10 
11 #运行结果
12 (1, 2, 3, 4, 5) <class tuple>
13 (a, b, c, d) <class tuple>
动态参数形式一
技术分享
 1 #转换成字典的动态参数形式,接收的参数要是能转换成字典形式的,就是类字典形式的数据,如键值对,字典
 2 
 3 def func(**kwargs):
 4     print(kwargs,type(kwargs))
 5 
 6 func(a=11,b=22)
 7 
 8 date_ex2={a:111,b:222}
 9 func(**date_ex2)
10 
11 #运行结果
12 {b: 22, a: 11} <class dict>
13 {b: 222, a: 111} <class dict>
动态参数形式二
技术分享
 1 #根据传的参数转换成元组和字典的动态参数形式,接收的参数可以是任何形式。
 2 def func(*args,**kwargs):
 3     print(args, type(args))
 4     print(kwargs,type(kwargs))
 5 
 6 func(123,321,a=999,b=666)
 7 
 8 date_ex3={a:123,b:321}
 9 func(**date_ex3)
10 
11 #运行结果
12 (123, 321) <class tuple>
13 {b: 666, a: 999} <class dict>
14 () <class tuple>
15 {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表达式

7.内置函数

Python 函数

原文:http://www.cnblogs.com/olivexiao/p/6522870.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!