zoukankan      html  css  js  c++  java
  • 第二模块 练习题

    1. 写函数,计算传入数字参数的和。

    def calc(x,y):
        res = x+y
        return  res
    a = calc(10,5)
    print(a)
    View Code

    2. 写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

    a = [1,2,3,4,5,6,7,8]
    def func(l):
        return l[1::2]
    print(func(a))
    View Code

    3.写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

    def func(s):
        if len(s)>5:
            print('%s>5'%s)
        elif len(s)<=5:
            print('%s<=5'%s)

    4. 写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

    def func(n):
        return n[:2]

    5. 写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数,并返回结果。

    context = input ('>>>')
    
    def func(arg):
        dic = {'数字':0,'字母':0,'空格':0,'其他':0}
        for i in arg:
            if i.isdigit():
                dic['数字'] +=1
            elif i.isalpha():
                dic['字母'] +=1
            elif i.isspace():
                dic['空格'] +=1
            else:
                dic['其他'] +=1
        return dic
    print(func(context))
    View Code

    6.写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作(进阶)

    import os
    file_name = input('请输入文件名:')
    be_modify = input('请输入要修改的内容:')
    af_modify = input('请输入要替换的内容:')
    
    def func(file, be_f, af_f):
        with open('file','r',encoding='utf-8') as f_read, open(file +'new','w',encoding='utf-8')as f_write:
            for line in f_read:
                if be_f in line:
                    new_line = line.replace(be_f,af_f)
                    f_write.write(new_line)
                else:
                    f_write.write(line)
            os.remove(file_name)
            os.rename(file_name +'new', file_name)
    func(file_name, be_modify, af_modify)
    View Code

    7.写一个函数完成三次登陆功能,再写一个函数完成注册功能

    ef regist():
        while True:
            user = input('user:').strip()
            if not user : continue
            else:
                break
        pwd = input('pwd:').strip()
        dic = ('注册账号:(),密码:()'.format(user, pwd))
        return dic
    print(regist())
    
    def login():
        count = 0
        while count <3:
            username = input("请输入用户名:")
            password = input("请输入密码:")
            if username == 'alex'and password =="abc123":
                print('登录成功')
            else:
                print('登录失败')
            count +=1
    login()
    View Code

    8. 写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容。

    def shifou_space(args):
        ret = True
        for i in args:
            if i.isspace():
                ret = False
                break
        return  ret
    result = shifou_space("21 31")
    print("有空格",result)
    View Code

    9.写函数,返回一个扑克牌列表,里面有52项,每一项是一个元组。

    def card():
        temp_list = []
        card = []
        for i in range(2,11):
            temp_list.append(i)
        temp_list.extend(["J","Q","K","A"])
        for i in temp_list:
            for card_type in ["黑桃",'红桃','方块','梅花']:
                a = (card_type,i)
                card.append(a)
    
        return  card
    res = card()
    print(res)
    View Code

    10.写函数,传入n个数,返回字典{‘max’:最大值,’min’:最小值}

    def func(*args):
        the_max = args[0]
        the_min = args[0]
        for i in args:
            if i > the_max:
                the_max = i
            elif: i< the_min:
                the_min = i
        return {'max':the_max,'min':the_min}
    res = func(1,2,3,4,5)
    print(res)

    11. 写函数,专门计算图形的面积_

    • 其中嵌套函数,计算圆的面积,正方形的面积和长方形的面积

    • 调用函数area(‘圆形’,圆半径) 返回圆的面积

    • 调用函数area(‘正方形’,边长) 返回正方形的面积

    • 调用函数area(‘长方形’,长,宽) 返回长方形的面积

    import  math
    def area(name,*args):
        def area_rectangle(x,y):
            return ("长方形的面积为:",x*y)
        def area_square(x):
            return("正方形的面积为:",x**2)
        def area_round(r):
            return("圆形的面积为:", math.pi*r*r)
        if name == '长方形':
            return area_rectangle(*args)
        elif name =='正方形':
            return  area_square(*args)
        elif name == '圆形':
            return  area_round(*args)
    print(area('长方形',2,3))
    print(area('正方形',2))
    print(area('圆形',6))
    View Code

    12. 写函数,传入一个参数n,返回n的阶乘_

    def calc(n):
        sum =1
        for i in range(n,0,-1):
            sum = sum *i
        return sum
    print(calc(7))
    View Code

    13. 编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码

    dic = {
        'username': None,
        'status': False
    }
    
    def wrapper(f):
        def inner(*args,**kwargs):
            if dic['status'] == True:
                ret = f(*args,**kwargs)
                return  ret
            else:
                i = 0
                while i<3:
                    username = input('请输入你的用户名:').strip()
                    password = input('请输入你的密码:').strip()
                    with open('log1',encoding='utf-8')as f1:
                        for j in f1:
                            j_li = j.strip().split()
                            if username == j_li[0] and password == j_li[1]:
                                dic['username'] =username
                                dic['status'] = True
                                ret = f(*args,**kwargs)
                                return  ret
                            else:
                                print('账号或密码错误,你还有%d次机会请重新输入。。。')%(2-i)
                                i +=1
            return inner
    @wrapper
    def articel():
        print('文章')
    @wrapper
    def diary():
        print('日记')
    articel()
    diary()
    View Code
  • 相关阅读:
    textarea中的空格与换行
    js判断微信内置浏览器
    关于express4不再支持body-parser
    html5 geolocation API
    屏幕密度与分辨率
    nodebeginer
    手机浏览器下IScroll中click事件
    iphone手机上的click和touch
    AngularJS学习笔记一
    不用bootstrap实现居中适应
  • 原文地址:https://www.cnblogs.com/kissfire008/p/11766188.html
Copyright © 2011-2022 走看看