創(chuàng)建函數def , define 縮寫,用來定義函數。
①無參函數
def function()
? ? print("你好")
function()
②有參函數
def max(a,b,c):? ? ? ? #形參
? ? if a > b and a > c:
? ? ? ? print(a)
? ? if b > a and b > c:
? ? ? ? print(b)
? ? if c > b and c > a:
? ? ? ? print(c)
max(12,52,25)? ? ? ? ? #實參
③有返回值函數的調用
def max(a,b):
? ? if a > b:
? ? ? ? return a
? ? else:
? ? ? ? return b
i=int(input("請輸入第一個數字:"))
j=int(input("請輸入第二個數字:"))
c=max(i,j)
print(c)
m=type(c)
print(m)
返回值的函數,對比type()。
④練習
練習1:編寫一個函數,檢查獲取傳入列表或元組對象的偶數。并將其作為新列表返回給調用者。
步驟:創(chuàng)建列表1——新空列表——定義函數——添加條件——返回值添加到新列表——運用函數——接收新列表——輸出新列表。
list1=[12,6,89,54,61,52,32,14,70,55,60,56,20]
new_list2=[]
def lis(lists):
? ? for i in lists:
? ? ? ? if i%2==0:
? ? ? ? ? ? new_list2.append(i)
? ? return new_list2
m=lis(list1)
print(m)
練習2:編寫一個函數,檢查傳入列表的長度,如果大于3,那么僅保留前2個長度的內容,并將新內容返回給調用者。
步驟:定義函數-建立條件并返回指定的值-創(chuàng)建列表-應用函數-接收新列表-輸出新列表。
def jiequ(lists):
? ? if len(lists)>3:
? ? ? ? return list1[:2]
list1=[12,6,89,54,61,52,32,14,70,55,60,56,20]
new_list=jiequ(list1)
print(new_list)
⑤global的作用是使局部變量變?yōu)槿肿兞俊?/p>