1. 程式人生 > >四、python之函數詳解

四、python之函數詳解

list global pan line ice see war -s span

一、函數

1.說白了就是把一組代碼合到一起,可以實現某種功能,需要再用到這種功能的話,直接調用這個函數就行
2.函數、方法是一回事
3.定義一個函數的格式是:def+函數名+()
4.函數必須調用了之後才能執行

eg:

my_open
fw = open(‘a.txt‘,‘a+‘)
fw.seek(0)

all_users = {} # 用來存放所有的用戶名和密碼
def read_users(file_name):#括號裏面是形式參數,其實就是一個變量
#函數體
print(file_name)
with open(file_name) as fr:
for line in fr:
up = line.strip().split(‘,‘) # 分隔賬號密碼
# print(‘分隔完之後的賬號密碼‘,up)
s_username = up[0] # 賬號
s_pwd = up[1] # 密碼
all_users[s_username] = s_pwd
print(‘調用函數之前:‘,all_users)
read_users(‘a.txt‘)#調用函數傳進去的參數叫做實際參數,簡稱實參
#函數名加上括號就是調用,函數需調用之後才能執行
print(‘調用函數之後:‘,all_users)

簡單寫

def hello(name):
#必填參數,位置參數
print(‘hello %s‘%name)
hello(‘鄭爽‘)

eg1:

def reg(name,age,sex=‘男‘):
age、name必填參數,位置參數
sex是默認值參數,不是必傳
print(‘hi %s,age is %s,sex is %s‘%(name,age,sex))
reg(‘小迪‘,19,‘nan‘)

eg2
5.*args#可變參數

eg:

def post(*args):
可變參數,也叫參數組,也不是必填的,它接收到的是一個元組
它把調用函數時穿進去的每一個參數都放到一個元組裏
print(args)
post(‘001‘,‘denglu‘,‘http://www.baiudd.com‘,‘post‘,‘a=1‘)
post(‘001‘,‘denglu‘)
post(‘001‘,‘denglu‘,‘post‘)
post(‘001‘)
post()
def other(name,age,country=‘china‘,*args):
print(name)
print(age)
print(country)
print(args)
other(‘wubing‘,‘999‘)

eg:

def other(name,age,country=‘china‘,*args):
print(name)
print(age)
print(country)
print(args)
other(‘‘)

6.**kwargs,關鍵字參數,接收的是一個字典,調用得用xx=11

傳入字典調用的時候就得寫**{‘age‘:18,‘name‘:‘xiaodi‘}
d = {‘age‘:18,‘name‘:‘xiaodi‘}
def kw(**kwargs):
print(kwargs)
kw()

eg:

def other2(name,country=‘china‘,*args,**kwargs):
#如果必填參數、默認值參數、可變參數和關鍵字參數你要一起用的話,必須參照必填參數、默認值參數、可變參數和關鍵字參數的順序接受,否則就報錯
print(name)
print(country)
print(args)
print(kwargs)
other2(‘wubing‘)
other2(‘xiaodi‘,‘beijing‘,‘python‘,‘yin‘,user = ‘ywq‘)

7.關鍵字參數調用

eg:

def write(filename,model,ending,user,os,money,other):
print(filename)
print(model)
print(ending)
print(user)
print(os)
print(money)
print(other)
write(os=‘windows‘,user=‘wubing‘,model=‘w‘,filename=‘a.txt‘,ending=‘utf-8‘,money=222,other=‘hahah‘)

8.函數的返回值

def plus(a,b):
return函數
1.調用碰到return,立即結束這個函數
2.調用完函數之後,返回計算的結果
3.函數可以沒有返回值,如果沒有返回值的話,默認返回none
4.如果這個函數的處理結果需要在別的地方用到,那就需要給函數返回值
5.如果函數return多個值得話,那麽他會把多個值放到一個元祖裏面去
c = a+b
return c

print(c)

plus(1,2)

eg:

score1 = 50
score2 = 90
def echo(sum):
print(‘總分是%s‘%sum)
res = plus(score1,score2)
print(res)
echo(res)
lis = [5,2,6,44,77]
print(lis.sort)

9.小程序
#1、判斷小數
# 1.92
# -1.988

def is_float(s):
‘‘‘
這個函數是用來判斷傳入的是否為小數,包括正小數和負小數
:param s: 傳入一個字符串
:return: True or False
‘‘‘
s = str(s)
if s.count(‘.‘)==1:#判斷小數點個數
sl = s.split(‘.‘)#按照小數點進行分割
left = sl[0]#小數點前面的
right = sl[1]#小數點後面的
if left.startswith(‘-‘) and left.count(‘-‘)==1 and right.isdigit():
lleft = left.split(‘-‘)[1]#按照-分割,然後取負號後面的數字
if lleft.isdigit():
return True
else:
return False
elif left.isdigit() and right.isdigit():
#判斷是否為正小數
return True
else:
return False
10.全局變量和局部變量
# score3 = [1,2,3,4,5]
# score3 = {"id":1}
score3 = 100
def my_open():
#在函數裏面定義變量叫局部變量,它只能在函數裏面用
#出了該函數外,就不能使用了
#在函數外面定義的變量,是全局變量,在函數內也可以使用
#如果想在函數裏面修改全局變量的值,那麽要先用global關鍵字聲明
#要修改全局變量是int、string的話,必須得寫global
#如果是字典和list的話,要修改的話,不能加global
fw = open(‘a.txt‘,‘a+‘)
fw.seek(0)
print(‘score3‘,score3)
d={‘id‘:2}
d[‘price‘]=99

def hh():
print(‘修改商品...‘)
def cc():
print(‘添加商品...‘)
def query():
print(‘查詢商品。。。‘)
menu= {
‘1‘:hh,
‘2‘:cc,
‘3‘:query
}
chioce = input(‘輸入編號‘)
menu[chioce]()
 

四、python之函數詳解