Python learning function object, and the nested function job closure function

1, the function object code is optimized if the multibranched Lianshu

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, write counter function is called once added to the original requirements on the basis of a

Tips:
the I: knowledge need to use: nonlocal closure function +
II: Core functions are as follows:

DEF counter ():
X + =. 1
return X
claim final effect similar
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())

Guess you like

Origin www.cnblogs.com/leilijian/p/12533242.html