3.20作业

今日作业:

1、函数对象优化多分支if的代码练熟

基本数学运算小程序:

def sub(x, y):
    res = x - y
    print(res)


def mul(x, y):
    res = x * y
    print(res)


def divi(x, y):
    res = x / y
    print(res)


dict1 = {
    0: ('退出', None),
    1: ('相加', sum),
    2: ('相减', sub),
    3: ('相乘', mul),
    4: ('相除', divi),
}
tage = True
while tage:
    x = int(input('输入第一个数: ').strip())
    y = int(input('输入第二个数: ').strip())
    for key, value in dict1.items():
        print(key, value[0])
    res = input('请输入命令: ').strip()
    choice = int(res)
    if choice == 0:
        break
    if choice not in dict1:
        print('输入命令不存在!')
        continue

    else:
        result = dict1.get(choice)[1](x, y)
        print(result)

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 f1():
    x = 0

    def counter():
        nonlocal x
        x += 1
        return x

    return counter


counter = f1()
print(counter())
print(counter())
print(counter())
print(counter())
print(counter())
posted @ 2020-03-20 20:00  风起千寻  阅读(154)  评论(0编辑  收藏  举报