1、函数对象优化多分支if的代码练熟
def log_in():
print('登录功能')
def register():
print('注册功能')
def check_balance():
print('查询余额')
def withdraw():
print('提现')
def transfer():
print('转账')
cmd_dic = {
'0':('退出',exit),
'1':('注册',register),
'2':('登录',log_in),
'3':('查询余额',check_balance),
'4':('提现',withdraw),
'5':('转账',transfer)
}
while True:
for k,v in cmd_dic.items():
print('{:>4} {}'.format(k,v[0]))
cmd = input('请输入命令编号:').strip()
if not cmd.isdigit():
print('必须输入数字')
elif cmd in cmd_dic:
cmd_dic.get(cmd)[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 outter():
x=0
def counter():
nonlocal x
x = x + 1
return x
return counter
counter = outter()
print(counter())
print(counter())
print(counter())
print(counter())
print(counter())