python算法技巧学以致用3——异常处理与函数整理

python算法技巧学以致用3——异常处理与函数整理,第1张

目录

1. 使用raise Excepytion,并保存异常的错误信息,请使用程序实例说明:

2. 请说明assert的功能,并用程序实例来说明:

3. lambda函数的使用:

4. 请说明在调用函数时,何谓关键词参数?本质上关键词参数是字典形式(dict):

5. 设计可以传递任意数量参数的函数,代码如下:

6. 设计一个upper()的装饰器,用@upper直接定义装饰器的名称:


1. 使用raise Excepytion,并保存异常的错误信息,请使用程序实例说明:
import traceback

def passward(pwd):
#检查密码长度必须是5到8个字符
    pwdlen = len(pwd)
    if pwdlen<5:
        raise Exception('The length of password is not enough!')
    if pwdlen>8:
        raise Exception('The length of password is not enough!')
    print('The length of password is good!')

for pwd in ('aabbccddee','aabbcc','aabb'):
# 测试系列密码值
    try:
        passward(pwd)
    except Exception as err:
        errlog = open('errtxt.txt','a')         # 开启错误文件
        errlog.write(traceback.format_exc())    # 写入错误文件
        errlog.close()                          # 关闭错误文件
        print('将Traceback写入错误文件errtxt.txt完成。')
        print('密码长度检查异常发生:'+str(err))
2. 请说明assert的功能,并用程序实例来说明:
class Banks():
#定义银行类别
    title = 'KUD bank'
    def __init__(self, uname, money):
        self.name = uname
        self.balance = money

    def save_money(self, money):
        assert money>0, '存款money必须大于0'
        self.balance += money
        print('存款',money,'完成')

    def withdraw_money(self, money):
        assert money>0, '提款money必须大于0'
        assert money

3. lambda函数的使用:

1)使用sorted配合lambda将列表正值额度元素从小到大排序,负值的元素从大到小排序:

list = [-4,-1,4,8,3,9,-8,-6,5,-2,0]
sorted_list = sorted(list, key=lambda x:(x<0, abs(x)))
print(sorted_list)

2)说明map(func, iterable)函数的用法,代码如下:

mylist = [5,10,20,30,40,50]
squarelist = list(map(lambda x:x**2, mylist))
print('列表的平方值:', squarelist)

3)说明filter(func,iterable)主要用于筛选序列,代码如下:

mylist = [5,10,15,20,25,50]
oddlist = list(filter(lambda x:x%2==1, mylist))
print('奇数列表:', oddlist)
4. 请说明在调用函数时,何谓关键词参数?本质上关键词参数是字典形式(dict):
def interest(interest_type,subject):
    #显示兴趣和主题
    print('我的兴趣是'+interest_type)
    print('在'+interest_type+'中,最喜欢的是'+subject)
    print( )

interest(interest_type = '旅游', subject = '敦煌')
interest(subject = '敦煌', interest_type = '旅游') #位置更动
hobby = '旅游'
place = '敦煌'
interest(hobby,subject = place)
5. 设计可以传递任意数量参数的函数,代码如下:

*toppings是指函数可以有任意数量的参数,本质是元组(tuple);

**toppingsnumber是指函数可以有任意数量的关键词参数,本质是字典(dict);

def beef_nooodle(*toppings, **toppingsnumber):
    #列出制作牛肉面的配料
    print('牛肉面所加的配料如下:')
    print(' '.join(toppings))
    print(toppings)
    print(toppingsnumber)

beef_nooodle('牛肉','牛肉=10')
beef_nooodle('牛肉','辣椒','葱花',牛肉=10,辣椒=3,葱花=10)
6. 设计一个upper()的装饰器,用@upper直接定义装饰器的名称:
def upper(func):            #装饰器
    def newFunc(args):
        oldresult = func(args)
        newresult = oldresult.upper()
        print('函数名称:',func.__name__)
        print('函数参数:',args)
        return newresult
    return newFunc
@upper                      # 设定装饰器
def greeting(string):       # 问候函数
    return string
print(greeting('Hello! iPone!'))

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/713901.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)