20.03.20作业
1、函数对象优化多分支if的代码练熟
示例1:用户功能选择优化
#!/usr/bin/env python # -*- coding:utf-8 -*- from prettytable import PrettyTable def login(): print('登录功能!') def save(): print('存钱功能!') def transfer(): print('转账功能!') def withdraw(): print('取钱功能!') def check_banlance(): print('查询余额功能!') def register(): print('注册功能!') func_choice= { '0': ('退出', None), '1': ('登录', login), '2': ('存钱', save), '3': ('转账', transfer), '4': ('取钱', withdraw), '5': ('查询余额', check_banlance), '6': ('注册', register) } def atm_interface(): while True: tb = PrettyTable(field_names=['功能编号', '功能名称']) for k in func_choice: tb.add_row([k, func_choice[k][0]]) print(tb) user_choice = input('请输入功能编号:').strip() if not user_choice.isdigit(): print('请输入一个正整数!') continue elif user_choice == '0': break elif user_choice in func_choice: func_choice[k][1]() else: print('该功能尚未支持!') _continue = input('是否继续(y,n):').strip().lower() if _continue == 'y': continue else: break atm_interface()
示例2:求圆的周长和面积
#!/usr/bin/env python #-*- coding:utf-8 -*- from math import pi def circle(radius,action=0): """ action参数:(0,1) 0 -->求圆的周长 2*pi*radius 1 -->求圆的面积 pi*(radius**2) """ def perimeter():return 2*pi*radius def area():return pi*(radius**2) if action == 0: res = perimeter() else:res = area() return res print('半径为4的圆的周长为:{:.2f}'.format(circle(4))) print('半径为6的圆的面积为:{:.2f}'.format(circle(6,action=1)))
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
实现:
#!/usr/bin/env python #-*- coding:utf-8 -*- """ 计数器功能 """ from random import randint def outter(): ct = 0 def count(): nonlocal ct ct += 1 print('当前计数次数:{}'.format(ct)) return count count = outter() for i in range(randint(0,5)): count()