- 函數中存在默認參數,調用函數時,可以不傳參數:
def db_connect(ip,port=3306):
print(ip,port)
db_connect('118.24.3.40',3307)
db_connect('118.24.4.40')
結果顯示
118.24.3.40 3307
118.24.4.40 3306
現在寫一個簡單的判斷小數的函數
def check_float(s):
s=str(s)
if s.count('.')==1:
s_split=s.split('.')
left,right=s_split
if left.isdigit() and right.isdigit():
return True
elif left.startswith('-') and left[1:].isdigit() \
and right.isdigit():
return True
return False
print(check_float(1.2))
print(check_float(-1.2))
print(check_float('12.3'))
print(check_float('-12.1'))
print(check_float('023'))
print(check_float('-023'))
2.位置參數
def db_connect(ip,user,password,db,port):
print(ip)
print(user)
print(password)
print(db)
print(port)
db_connect(user='nini',db='87667',ip='123.23.233.23',password='123456',port='22')
db_connect('12.23.22.22','didi',password='2323323',db='334',port='6732')
第一種裏面的參數的位置可變化。
第二種的順序必須按照位置來
3.可變參數
函數中參數組:
可變參數,不必傳,傳入的元素全部放到元組裏面,不限制參數個數,使用參數比較多情況,傳入元素存在元組裏面
def sen_sms(*phone_num):
print(phone_num)
sen_sms()
sen_sms(123)
sen_sms(123,223,44,33,)
def sen_mes(*args):
for p in args:
print(p)
sen_mes(12,23,23,24)
4.關鍵字參數
def send_sms2(**phone_num):
print(phone_num)
send_sms2(name='xiix',sex='nan')
send_sms2(addr='北京',courtry='中國',c='abc',f='kkk')