Python基礎(chǔ)-函數(shù)
1.函數(shù)定義
def sum(a,b):
c = a+b
return c
2.參數(shù)傳值
1.順序傳入
def show(name,age,sex):
print("姓名:",name,"年齡:",age,"性別",sex,)
show("python","男","18") #輸出:性別:python 年齡:男 性別:18
2.關(guān)鍵詞
show("張山",sex = "男", age = "18")
3.默認(rèn)參數(shù) (默認(rèn)參數(shù)必須放在參數(shù)列表的末位)
def show(name,sex,age=18):
print("姓名:",name,"年齡:",age,"性別",sex,)
show (name = "python",sex = "男") #輸出:性別:python 年齡:18 性別:男
show (name = "python",sex = "男", age = 25) #輸出:性別:python 年齡:男 性別:25
4.不定長參數(shù)
def add(*args):
for i in args: #args 為一個(gè)元組
sum = sum+i
return sum
d = add(2,3,4,6,7)
print(d) #輸出:12
3.內(nèi)置函數(shù)
1.數(shù)字相關(guān)
abs(a) #求取絕對值
max(list) #求取list最大值
min(list) #求取list最小值
sum(list) #求取list元素的和
sorted(list) #排序 返回排序后的list
len(list) #list的長度
divmod(a,b) #獲取商和余數(shù) divmod(5,2)----(2,1)
pow(a,b) #獲取乘方數(shù) pow(2,3)-----8
round(a,b) #獲取制定位數(shù)的小數(shù),a代表浮點(diǎn)數(shù),b代表保留的位數(shù) round(3.1415926,2)---3.14
rang(a,b) #
2.類型轉(zhuǎn)化
int(str)
float(int/str)
str(int)
bool(int) #bool(0)---False bool(None)---False
bytes(str,code) #bytes("abc","utf-8")----b"abc"
list(iterable) #轉(zhuǎn)化成list list((1,2,3)) -----[1,2,3]
iter(iterable) #返回一個(gè)可迭代的對象 iter([1,2,3])---<list iterator object at 0x000000003813B00>
dict(iterable) #轉(zhuǎn)化成字典 dict(("a",1),("b",2))----{"a":1,@"b":2}
enumerate(iterable) #返回一個(gè)枚舉對象
tuple(iterable) #轉(zhuǎn)化成tuple tuple([1,2,3])-----(1,2,3)
set(iterable) #轉(zhuǎn)出成set set([1,2,3])----{1,2,3} set({"a":1,"b":2})----{"a","b"}
hex(int) #轉(zhuǎn)出成16進(jìn)制
oct(int) #轉(zhuǎn)化成8進(jìn)制