1. 程式人生 > 實用技巧 >ptthon函式例項應用案例

ptthon函式例項應用案例

一、函式的用法

1. 函式可以做賦值

def func():
    print('from func')
f=func()

2.函式可以當做引數被呼叫

3.可以放入列表等當中

1 l=[func,]     #作為元素時,函式名不加括號
2 l[0]()       #呼叫
View Code

4.案例1:

  1)小白寫的程式 

 1 def login():
 2     print('登入功能')
 3 def transfer():
 4     print('轉賬功能')
 5 def select():
 6     print('查詢餘額')
 7 while True:
8 print('''' 9 0 退出 10 1 登入 11 2 轉賬 12 3 查詢餘額 13 ''') 14 chice=input('請輸入命令編號:').strip() 15 if not chice.isdigit(): 16 continue 17 if chice=='0': 18 break 19 elif chice=='1': 20 login() 21 elif chice=='2': 22 transfer() 23 elif
chice == '3': 24 select() 25 else: 26 print('輸入指令不存在')
View Code

  2)我進一步優化(程式寫死後新增功能不方便,一個功能寫一個函式)

 1 def login():
 2     print('登入功能')
 3 def transfer():
 4     print('轉賬功能')
 5 def select():
 6     print('查詢餘額')
 7 func_dict={
 8     '1':login,
 9     '2':transfer,
10     '
3':select 11 } 12 while True: 13 print('''' 14 0 退出 15 1 登入 16 2 轉賬 17 3 查詢餘額 18 ''') 19 chice=input('請輸入命令編號:').strip() 20 # if not chice.isdigit(): 21 # continue 22 # if chice=='0': 23 # break 24 # elif chice=='1': 25 # login() 26 # elif chice=='2': 27 # transfer() 28 # elif chice == '3': 29 # select() 30 # else: 31 # print('輸入指令不存在') 32 if chice in func_dict.keys(): 33 func_dict[chice]() 34 else: 35 print('輸入指令不存在')
View Code

  3)高手的優化

 1 def login():
 2     print('登入功能')
 3 def transfer():
 4     print('轉賬功能')
 5 def select():
 6     print('查詢餘額')
 7 func_dict={
 8     '0':['退出',None],
 9     '1':['登入',login],
10     '2':['轉賬',transfer],
11     '3':['查詢餘額',select]
12 }
13 while True:
14     # print(''''
15     # 0 退出
16     # 1 登入
17     # 2 轉賬
18     # 3 查詢餘額
19     # ''')
20     for k in func_dict:      #解放以上print內容
21         print(k,func_dict[k][0])
22     chice=input('請輸入命令編號:').strip()
23     # if not chice.isdigit():
24     #     continue
25     if chice=='0':
26         break
27     # elif chice=='1':
28     #     login()
29     # elif chice=='2':
30     #     transfer()
31     # elif chice == '3':
32     #     select()
33     # else:
34     #     print('輸入指令不存在')
35     if chice in func_dict.keys():
36         func_dict[chice][1]()
37     else:
38         print('輸入指令不存在')
View Code

5.函式的巢狀呼叫及定義

 1 def bijiao():
 2 # 對4個數字比較大小
 3     def max2(x,y):
 4         if x>y:
 5             return x
 6         else:
 7             return y
 8     def max4(a,b,c,d):
 9         res1=max2(a,b)
10         res2=max2(res1,c)
11         res3=max2(res2,d)
12         return res3
View Code

優點:減少程式碼量,清晰明瞭