今日作业:
1、函数对象优化多分支if的代码练熟
def login():
print("登录功能")
def register():
print("注册功能")
def transfer_accounts():
print("转账功能")
def check_banlance():
print("查询功能")
def withdraw_deposit():
print('提现')
def recharge():
print('充值')
# func_dic = {
# '0': ('退出', exit),
# '1': ('登录', login),
# '2': ('注册', register),
# '3': ('转账', transfer_accounts),
# '4': ('查询', check_banlance),
# '5': ('提现', withdraw_deposit),
# '6': ('充值', recharge),
# }
# 利用字典生成式生成
func_list = [
('退出', exit),
('登录', login),
('注册', register),
('转账', transfer_accounts),
('查询', check_banlance),
('提现', withdraw_deposit),
('充值', recharge)
]
func_dic = {key: value for key, value in zip(range(len(func_list)), func_list)}
# print(func_dic)
def login():
while True:
for key, value in func_dic.items():
print(f'{key}:{value[0]}')
cmd = input("输入命令编号>>:").strip()
if not cmd.isdigit():
print('请输入数字实现命令')
continue
if cmd not in func_dic:
print("输入命令不存在")
continue
func_dic[cmd][1]()
2、编写计数器功能,要求调用一次在原有的基础上加一
温馨提示:
I:需要用到的知识点:闭包函数+nonlocal
II:核心功能如下:
def counter():
x+=1
return x
def outer(number):
init_number = 0
def counter():
nonlocal init_number
init_number = number + init_number
return init_number
return counter
func_counter = outer(1) # 这里把counter局部的内存地址声明成全局, func_counter全局共享
print(func_counter()) # 1
print(func_counter()) # 2
print(func_counter()) # 3
print(func_counter()) # 4
print(func_counter()) # 5
要求最终效果类似
print(couter()) # 1
print(couter()) # 2
print(couter()) # 3
print(couter()) # 4
print(couter()) # 5