1、函数对象优化多分支if的代码练熟
def login():
print('登录功能')
def transfer():
print('转账功能')
def check_banlance():
print('查询余额')
def withdraw():
print('提现')
def register():
print('注册')
func_dic = {
'0': ['退出', None],
'1': ['登录', login],
'2': ['转账', transfer],
'3': ['查询余额', check_banlance],
'4': ['提现', withdraw],
'5': ['注册', register]
}
while True:
for k in func_dic:
print(k, func_dic[k][0])
choice = input('请输入命令编号:').strip()
if not choice.isdigit():
print('必须输入编号')
continue
if choice == '0':
break
if choice in func_dic:
func_dic[choice][1]()
else:
print('输入的指令不存在')
2、编写计数器功能,要求调用一次在原有的基础上加一
"""
温馨提示:
I: 需要用到的知识点:闭包函数 +
nonlocal
II: 核心功能如下:
def counter():
x += 1
return x
要求最终效果类似
print(couter()) # 1
print(couter()) # 2
print(couter()) # 3
print(couter()) # 4
print(couter()) # 5
"""
def number_func():
x = 0
def counter():
nonlocal x
x += 1
return x
return counter
counter = number_func()
print(counter())
print(counter())
print(counter())
print(counter())
print(counter())