Python学习笔记 之 函数

函数


 

函数式编程最重要的是增强代码的重用性和可读性

  1.  定义和使用

def 函数名(参数):

  ...

  函数体

  ...

  返回值

 

函数的定义主要有如下要点:

def:表示函数的关键字

函数名:函数的名称,日后根据函数名调用函数

函数体:函数中进行一系列的逻辑计算

参数:为函数体提供数据

返回值:当函数执行完毕后,可以给调用者返回数据

 

举例:

1 def mail():
2     n = 123
3     n += 1
4     print(n)
5 mail()
6 f = mail
7 f()

结果:

124

124

1-1 返回值

函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。

1 def show():
2     print('a')
3     return [11,22]
4     print('b')
5 show()

结果:

a   

1-2 参数

函数中有三种不同的参数:

  •  普通参数
  •  默认参数
  •  动态参数

普通参数

1 def show(a1,a2):
2     print(a1,a2)
3 
4 show(11,22)

结果:

11  22

默认参数:默认参数需要放在参数列表最后

1 def show(a1,a2=99):
2     print(a1,a2)
3 
4 show(11)

结果:

11  99

指定参数

1 def show(a1,a2):
2     print(a1,a2)
3 
4 show(a2=123,a1=190)

结果:

190  123

动态参数

1 def show(*arg):# * - 接收参数并转换元组
2     print(arg,type(arg))
3 
4 show(1,56,78,8979)

结果:

(1,56,78,8979) <class 'tuple'>

1 def show(**arg): #  ** - 接收参数并转换字典     
2     print(arg,type(arg))
3 
4 show(n1=78,uu=123)

结果:

{'uu': 123, 'n1': 78} <class 'dict'>

 

1 def show(*arg1,**args):# 一个*的在前,两*在后
2     print(arg1,type(arg1))
3     print(args,type(args))
4 
5 show(12,34,34,54,n9=33,n2=99)# 一个*的在前,两*在后

结果:

(12, 34, 34, 54) <class 'tuple'>

{'n2': 99, 'n9': 33} <class 'dict'>

 

1 def show(*arg1,**args):# 一个*的在前,两*在后
2     print(arg1,type(arg1))
3     print(args,type(args))
4 
5 l = (11,22,3,4)
6 d = {'n1':89,'k1':'hello'}
7 show(l,d)

结果:

((11, 22, 3, 4), {'k1': 'hello', 'n1': 89}) <class 'tuple'>

{} <class 'dict'>

很明显,结果不是我们想要的。关键是如果我们使用show(l,d)

那么和我们使用show(1,56,78,8979) 没有什么区别。所以,为了解决这种冲突问题,只需要在 l 前加一个*,在 d 前加两个 * 即可:

1 def show(*arg1,**args):# 一个*的在前,两*在后
2     print(arg1,type(arg1))
3     print(args,type(args))
4 
5 l = (11,22,3,4)
6 d = {'n1':89,'k1':'hello'}
7 show(*l,**d)

结果:

(11, 22, 3, 4) <class 'tuple'>

{'n1': 89, 'k1': 'hello'} <class 'dict'>

符合我们的要求

 

动态参数实现字符串格式化:

1 s1 = "{0} is {1}"
2 ret = s1.format('Young','handsome')
3 print(ret)

结果:

Young is handsome

 

1 s1 = "{0} is {1}"
2 l = ['Young','handsome2']
3 ret = s1.format(*l)
4 print(ret)

结果:

Young is handsome2

 

1 s1 = '{name} is {value}'# 字典这里就不是{0}、{1}了,而是用{key}、{value}
2 ret = s1.format(name='Young',value='handsome')
3 print('第一:',ret)
4 
5 s2 = '{name2} is {key}'
6 d = {'name2':'Young','key':'smart'}
7 ret = s2.format(**d)
8 print('第二:',ret)

结果:

第一: Young is handsome

第二: Young is smart

 

 2.  内置函数

any : 只要有一个是真的就是真的

 

 

ord chr配合使用

 

 

chr    ord    random.randint 可以生产验证码

 

enumerate

 

 eval

map

 

 

filter

1 li=[1,22,33,45,74,788]
2 def func(num):
3     if num>33:
4         return  True
5     else:
6         return False
7 n = filter(func,li)
8 print(list(n))

结果:

[45, 74, 788]

 

将列表中大于 33 的元素拿出来

 

 

 

 

posted @ 2016-08-27 21:37  雨纷纷草木深  阅读(228)  评论(0编辑  收藏  举报