码迷,mamicode.com
首页 > 编程语言 > 详细

python---函数

时间:2017-06-24 00:28:07      阅读:317      评论:0      收藏:0      [点我收藏+]

标签:固定   默认参数   过程   pre   imp   return   接收   数学   实参   

函数学习,要点总结如下:

1. 函数默认可以没有返回值,没有返回值则返回为None
2. 函数可以有多个返回值,类型可以不同,但其实多个返回值整体上是一个元组
3. 关键参数不能够写在位置参数前面
 1 # -*- coding:utf-8 -*-
 2 # LC
 3 
 4 import time
 5 #函数:
 6 def logger():               #定义日志函数
 7     time_format = %Y-%m-%d  %X        #定义时间格式
 8     time_current = time.strftime(time_format)       #抓取当前时间
 9     with open("log_file","a") as f:
10         f.write("%s this is end\n"%time_current)
11 
12 def func1():
13     """to declare the function"""           #说明这个函数是做什么的
14     print("this is function1")              #函数工作模块,逻辑
15     logger()
16     return 0                                    #函数返回值
17 
18 #过程:                #过程是没有返回值的函数,在python中,过程默认返回None
19 def func2():
20     """function 2"""
21     print("this is function2")
22     logger()
23     return 1,{"name":"lvcheng","age":"18"}      #可返回多个值
24 
25 x = func1()             #调用函数
26 y = func2()
27 print(x)
28 print(y)
29 
30 def func3(x,y,z):              #x,y为形参,同为位置参数
31     print(x,y,z)
32     return x,y,z
33 
34 func3(1,2,3)          #位置参数调用,位置需要与形参一一对应
35 func3(1,2,z=3)
36 func3(y=2,z=3,x=1)      #关键字调用,关键参数,与形参顺序无关
37 
38 #默认参数
39 def func4(x,y=3):        #y是默认参数
40     print(x)
41     print(y)
42 func4(1)
43 func4(1,5)
44 #默认参数可以不传递,如果有传递,则是传递的值
45 #用途 1,默认安装的时候,2, 链接数据库的端口号等
46 
47 #参数组,对于实参不固定函数的实现
48 def func5(*args):       # *是关键字,元组的方式传递
49     print(args)
50 
51 # *args接受N个位置参数,转换成元组的方式
52 
53 test1 = func5(1,2,3,4,5)    # 1,2,3,4,5以(1,2,3,4,5)元组的方式传递给args
54 test1 = func5(*[1,2,3,4])
55 
56 #参数组,以字典的方式实现
57 
58 def func6(**kwargs):
59     print(kwargs)
60     print(kwargs[name])       #取字典里的值
61     print(kwargs[age])
62 # **kwargs接收N个关键字参数,转换成字典的方式传递
63 
64 
65 test2 = func6(name="lc",age=9)          #必须传递关键字参数
66 test2 = func6(**{"name":"lc","age":10})
67 
68 
69 def func7(name,age=19,**kwargs):        #有形参,有默认参数,有参数组
70     print(name)
71     print(age)
72     print(kwargs)
73 
74 test3 = func7("lc",21,sex="M",hobby="girl")
75 test3 = func7("lc",sex="M",hobby="girl",age = 32)
76 
77 def func8(name,age=19,*args,**kwargs):
78     print(name)
79     print(age)
80     print(args)
81     print(kwargs)
82 
83 func8("lc",2,3,4,sex="M",hobby="money")

 

python---函数

标签:固定   默认参数   过程   pre   imp   return   接收   数学   实参   

原文地址:http://www.cnblogs.com/clv5/p/7072013.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!