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)