1、函数对象优化多分支if的代码练熟
def log_in(): print('登录功能') def register(): print('注册功能') def check_balance(): print('查询余额') def withdraw(): print('提现') def transfer(): print('转账') dic = { '0':{'退出',exit}, '1':{'注册',register}, '2':{'登录',log_in}, '3':{'查询余额',check_balance}, '4':{'提现',withdraw}, '5':{'转账',transfer} } while True: for k in dic: print(k,dic[k][0]) cmd = input('请输入命令编号:').strip() if not cmd.isdigit(): print('必须输入命令编号的数字,傻叉') continue if cmd == '0': break if cmd in dic: dic[cmd][1](name) else: print('没有此命令')
计算器累加
def f1(): x=0 def counter(): nonlocal x x += 1 return x return counter f2 = f1() print(f2()) print(f2()) print(f2()) print(f2()) print(f2())