1、函数
- 为什么要有函数?解决重复代码的编写问题。减少重复代码,加强代码维护。
- 写不写都等于返回了一个None,一定要有返回值,要不然会默认加一个None.
练习题1:两个数字比大小,如果大了,写xx>yy,如果等于xx==yy,小于xx<yy
普通的写法:
a=10
b=20
if a>b:
print("%s 大于 %s" %(a,b))
elif a==b:
print("%s 等于 %s"%(a,b))
else:
print("%s 小于 %s"%(a,b))
函数的写法:
def compare_two_nums(a,b):
if a>b:
print("%s 大于 %s" %(a,b))
elif a==b:
print("%s 等于 %s"%(a,b))
else:
print("%s 小于 %s"%(a,b))
compare_two_nums(10,30)
compare_two_nums(50,10)
compare_two_nums(10,10)
函数的定义:
def 函数名(x,y): #括号里面可以有参数也可以没有参数,个数:0-多个
函数体:完成数据操作或者计算的过程
return 计算的结果
练习题2:打印*号
def print_star(times):
if not isinstance(times,int):
return None
print("*"*times)
print_star(10)
def print_star(times):
if not isinstance(times,int):
return None
print("*"*times)
#print_star(10)
print("*"*-2)#输入的个数为负数的时候,输出的为空
练习题3:求两数之和
def add(a,b):
if not (isinstance(a,(int,float)) and isinstance(b,(int,float))):
return None
print(a+b)
add(1,2)
def add(a,b):
if not (isinstance(a,(int,float)) and isinstance(b,(int,float))):
return None
print(a+b)
add(1,2)
add(1.2,2.4)
常见的错误:
参数个数不对的情况:
- 缺少了参数的时候的报错
>>> def add(a):
... if not (isinstance(a,(int,float))):
... return None
... print(a)
... return a
...
>>> add()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() missing 1 required positional argument: 'a'
>>> add(1)
1
1
- 参数多余的时候也会报错
>>> add(1,2,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() takes 1 positional argument but 3 were given
函数返回2遍值
>>> def a():
... print(10)
... return 10
...
>>> a()
10
10
>>> print(a())
10
10
总结:在交互模式下,会自动打印return下面返回的值
2、不同的参数传递方式
def add(a,b):
if not(isinstance(a,(int,float)) and isinstance(b,(int,float))):
return None
print("a:",a)
print("b:",b)
add(1,2)
add(b=2,a=1)#命名参数,通过改变参数的位置来命名
解包的时候能用到:
3、默认值与非默认值
规则:带有默认值参数的参数必须在没有默认值参数的后面
>>> def print_sth(a,b="world"):
... print(a,b)
...
>>> print_sth("hello")
hello world
>>> print_sth("ni","hao")
ni hao
违反规则报错:
>>> def print_sth(b="world",a):
... print(a,b)
...
File "<stdin>", line 1
SyntaxError: non-default argument follows default argument
>>> def print_sth(b="world",a="hello"):
... print(a,b)
...
>>> print_sth()
hello world
>>> print_sth("hi")
hello hi
>>>
4、函数的参数个数未知
>>> def add(a,b,*c):
... print(type(c))
... print(c)
...
>>> add(1,2,3,4,5)
<class 'tuple'>
(3, 4, 5)
>>> add(1,2,3,4,5,6,7,8)
<class 'tuple'>
(3, 4, 5, 6, 7, 8)
>>> def add(a,b,*c):
... print(c)
... sum=0
... sum=a+b
... for i in c:
... sum+=i
... return sum
...
>>> add(1,2,3,4,5)
(3, 4, 5)
15
>>> def add(a,b,**kw):
... sum=0
... sum+=a
... sum+=b
... for i in kw.values():
... sum+=i
... return sum
...
>>> add(1,2,c=3)
6
>>> add(1,2,c=3,d=4)
10
>>> add(1,2,c=3,d=4,e=5)
15
>>> add(1,2,a=3,d=4,e=5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() got multiple values for argument 'a'
>>> def add(a,b,*args,**kw):
... sum=0
... sum+=a
... sum+=b
... for i in args:
... sum+=i
... for value in kw.values():
... sum+=value
... return sum
...
>>> add(1,2)
3
>>> add(1,2,3)
6
>>> add(1,2,3,4)
10
>>> add(1,2,3,4,d=5)
15
>>> add(1,2,3,4,d=5,e=6)
21
5、map是python的内置函数
map:表示把序列中的每一个元素,依次(分别)传给函数去做处理,处理后,放到一个list中
map() 会根据提供的函数对指定序列做映射。
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
map(function, iterable, …)
Python3返回迭代器
>>> for i in map(str,[1,2,3]):
... print(type(i),i)
...
<class 'str'> 1
<class 'str'> 2
<class 'str'> 3
>>> list(map(str,[1,2,3]))
['1', '2', '3']
>>> def add(num):
... return num+10
...
>>> map(add,[1,2,3,4])
<map object at 0x000001712FEAC0B8>
>>> list(map(add,[1,2,3,4]))
[11, 12, 13, 14]
6、filters是python的内置函数
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
filter(function, iterable)
function – 判断函数。
iterable – 可迭代对象。
返回列表。
>>> def is_letter(letter):
... if isinstance(letter,str):
... return True
... return False
...
>>> list(filter(is_letter,[1,2,"a","b",3]))
['a', 'b']
7、Lambda方法
>>> a=lambda x:x+1
>>> type(a)
<class 'function'>
>>> a(1)
2
>>> a=lambda x,y:x+y
>>> a(1,2)
3
一行代码:
>>> list(map(lambda x:x+10,[1,2,3,4]))
[11, 12, 13, 14]
8、reduce是python的内置函数
reduce() 函数会对参数序列中元素进行累积。
函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
reduce() 函数语法:
reduce(function, iterable[, initializer])
function – 函数,有两个参数
iterable – 可迭代对象
initializer – 可选,初始参数
返回函数计算结果。
>>> from functools import reduce
>>> a=lambda x:x+1
>>> type(a)
<class 'function'>
>>> a(1)
2
>>> a=lambda x,y:x+y
>>> a(1,2)
3
>>> reduce(a,[1,2,3,4])
10
>>> map(lambda x:x+10,[1,2,3,4])
<map object at 0x000001712FEAAF60>
>>> list(map(lambda x:x+10,[1,2,3,4]))
[11, 12, 13, 14]
>>> reduce(lambda x,y:x+y,[1,2,3,4])
10
第一次:x:1 y:2 x+y=3
第2次:x:3 y:3 x+y=6
第三次:x:6 y:4 x+y=10
第1次执行lambda:x=1 y=2 x+y=3
第2次执行lambda:x=3 y=3 x+y=6
第3次执行lambda:x=6 y=4 x+y=10
>>> lambda x:x+1
<function <lambda> at 0x000001712FEA5488>
>>>
>>> def func(x): #等价于:lambda x:x+1
... return x+1
...
>>> func(1)
2
>>> func=lambda x:x+1
>>> func(1)
2
>>> lambda x:x+1
<function <lambda> at 0x000001712FEA5598>
>>> def func(x):
... return x+1
...
>>> func(1)
2
>>> func=lambda x:x+1
>>> func(1)
2
>>> lambda x,y:x+y
<function <lambda> at 0x000001712FEA5620>
>>> def func(x,y):
... return x+y
...
>>> func(1,2)
3
>>> func=lambda x,y:x+y
>>> func(1,2)