函数

egon09.blog.51cto.com/9161406/1834777

函数式编程 def -- 逻辑结构化和过程化的一种方法

def _funcname(x)

  ###函数描述

  x +=1

  return x

 

##过程没有返回值的函数,在py中返回None,也可以当作函数看

##单个值,就是返回该object

##多个返回值,返回到一个元组中

##关键参数要写在位置参数后面,参数不能重复赋值

 

def test(*args)

  print(args)

 

 

 1 def func1():
 2     print("function1!!!!")
 3     return 1
 4 
 5 def prog1():
 6     print("This is a progress!")
 7 
 8 #_func = func1()
 9 #_prog = prog1()
10 
11 #print("From func1 %s\n"%_func)
12 #print("From func1 %s"%_prog)
13 import time
14 def logger():
15     time_format = '%Y-%m-%d %X'
16     time_current = time.strftime(time_format)
17     with open("a.txt","a+") as f:
18         f.writelines("%s End Action\n" %time_current)
19 
20 def _apptxt1():
21     print('Appe 1!')
22     logger()
23 
24 def _apptxt2():
25     print('Appe 22!')
26     logger()
27 
28 def _apptxt3():
29     print('Appe 333!')
30     logger()
31 
32 _apptxt1()
33 _apptxt2()
34 _apptxt3()
35 
36 def prt_list(list_name):
37     ### 打印list中的行
38     for index,item  in enumerate(list_name):
39         print(index, item)
40 
41 def app_list_to_f(list_name,file_name):
42     ### 添加list中的元素到文件中
43     with open(file_name, "a+") as f:
44         for index,item  in enumerate(list_name):
45             f.writelines(item)
46             f.writelines("\n")
47 
48 
49 _list1 = ["a","bbb","ccccc"]
50 _list2 = ["shanghai","hangzhou","hefei"]
51 
52 _file_name ="a.txt"
53 
54 prt_list(_list1)
55 prt_list(_list2)
56 
57 app_list_to_f(_list1,"a.txt")
58 
59 def test_args(x,*args):
60     print(x)
61     print (args)
62 
63 print(test_args(1,2,34,1,123))
64 
65 def test_dic(**dargs): ##把n个关键字和参数,转换为字典
66     print(dargs)
67 
68 test_dic(name='Louie',age=19,sex='M')
69 test_dic(**{"name":'Louie',"age":19})

   局部变量

# 函数内不能改全局变量,作用域在函数内部,函数完成之后就释放了

# 如果在函数内要改函数外的全局变量,要加golbal 在全局变量之前

# 列表,字典、集合都是可以在函数中将局部变量中改全局变量

 

 

高阶函数

函数的参数可以接受变量 -》把一个函数当作一个变量传给函数

return(函数)

def add(a,b,f):

  return f(a) +f(b)

 res = add(1,-3,abs)

print(res)

 

#有的函数不需要取名字,比如 calc = lambda X:X*3  / print(calc(44))

posted @ 2018-05-05 22:31  ywyin  阅读(117)  评论(0编辑  收藏  举报