python函数应用_python 函数应用
#函數(shù)的參數(shù)就是個(gè)變量
#定義函數(shù)的時(shí)候,使用關(guān)鍵字參數(shù),可以指定默認(rèn)值
def hello(name='reboot',age=1):
return 'hello %s,your age is %s' %(name,age)
print hello('reboot',3)
print hello(3,'reboot')
#print hello(age=3,name='reboot')
print hello('reboot')
def f(n):
count=1
for i in range(1,n+1):
count=i*count
return count
print f(5)
# *號(hào)開頭的參數(shù),收集所有的剩余參數(shù)(位置參數(shù)),組裝成元組
# **開頭的參數(shù),收集所有剩下參數(shù)(關(guān)鍵字參數(shù)),組裝成字典
def sum(name,*num):
print num
return sum
sum(111,2222,333)
#練習(xí)、函數(shù)add_all,把傳入的所有參數(shù)求和并打印
def count(*add_all):
count=0
for i in add_all:
count+=i
return count
print count(1,2,3,4,5)
def name(**dict):
print dict
name(name='reboot',teach='pc',age=30)
#排序 函數(shù)復(fù)用,利用冒泡來排序
def my_sort(arr,sort_fn):
for j in range(11):
for i in range(len(arr)-1):
if sort_fn(arr[i])>sort_fn(arr[i+1]):
arr[i],arr[i+1]=arr[i+1],arr[i]
return arr
arr=[1,22,3,55,99,0,4,7]
def sort_fn1(data):
return data
print my_sort(arr,sort_fn1)
arr2=[('xiaoming',29),('xiaohua',44),('xiaohong',99)]
def sort_fn2(data):
return data[1]
print my_sort(arr2,sort_fn2)
arr3=[{'name':'xiaohong','age':22},{'name':'pc','age':18},{'name':'xiaohua','age':99}]
def sort_fn3(data):
return data['age']
print my_sort(arr3,sort_fn3)
print sorted(arr3,key=sort_fn3) #sorted(待排序的list,決定根據(jù)元素的那個(gè)排序)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的python函数应用_python 函数应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: packetbeat oracle,pa
- 下一篇: 比较器的使用