苹果IT家园

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

1、定义函数

 1 def func1():#定义函数
 2     print('in the func1')
 3     return 0
 4 
 5 def func2():#过程是没有返回值的函数
 6     print('in the func2')
 7 
 8 x=func1()
 9 y=func2()
10 
11 print('from func1 return is %s' %x)
12 print('from func2 return is %s' %y)

运行结果

1 in the func1
2 in the func2
3 from func1 return is 0
4 from func2 return is None

2、通过函数向文本中追加内容

 1 #定义函数的好处:代码重用,保持一致性,可扩展性
 2 import time
 3 def logger():
 4    time_format = '%Y-%m-%d %X'#定义时间格式:年-月-日,X表示小时,分钟,秒
 5    time_current = time.strftime(time_format) #引用上面的时间格式
 6    with open('ab.txt','a+') as f: #a+表示向文件中追加内容
 7      f.write('%s end action\n' %time_current)
 8 
 9 def test1():
10     print('in the test1')
11     logger()
12 def test2():
13     print('in the test2')
14     logger()
15 def test3():
16     print('in the test3')
17     logger()
18 
19 test1()
20 test2()
21 test3()

运行结果

1 in the test1
2 in the test2
3 in the test3

文本文件ab.txt中追加的内容为:

1 2017-06-13 15:51:22 end action
2 2017-06-13 15:51:22 end action
3 2017-06-13 15:51:22 end action

 3、函数关键字、位置参数调用

 1 def test1():
 2     print('in the test1')
 3 def test2():
 4     print('in the test2')
 5     return 0
 6 def test3():
 7     print('in the test3')
 8     return 1,'hello',['alex','wupeiqi'],{'name':'alex'}
 9 
10 x=test1()
11 y=test2()
12 z=test3()
13 print(x)
14 print(y)
15 print(z)
16 
17 def test(x,y):
18     print(x)
19     print(y)
20 test(y=2,x=1) #关键字调用:与形参顺序无关
21 test(1,2) #位置参数调用:与形参一一对应
22 test(3,y=2)
23 #test(x=2,3) #关键参数不能写在位置参数前面

运行结果

 1 in the test1
 2 in the test2
 3 in the test3
 4 None
 5 0
 6 (1, 'hello', ['alex', 'wupeiqi'], {'name': 'alex'})
 7 1
 8 2
 9 1
10 2
11 3
12 2

 

posted on 2017-06-13 16:03  苹果IT家园  阅读(139)  评论(0)    收藏  举报