zoukankan      html  css  js  c++  java
  • 作业一

    3月24号

    # 作业:
    # 1、编写课上讲解的有参装饰器准备明天默写
    def auth(type):
        def inner(func):
            def wrapper(*args, **kwargs):
                name = input('your name>>>: ').strip()
                pwd = input('your password>>>: ').strip()
                if type == 'file':
                    print('基于文件的验证')
                    if name == 'egon' and pwd == '123':
                        res = func(*args, **kwargs)
                        return res
                    else:
                        print('user or password error')
                elif type == 'mysql':
                    print('基于mysql的验证')
                    return func(*args, **kwargs)
                elif type == 'ldap':
                    print('基于ldap的验证')
                    return func(*args, **kwargs)
                else:
                    print('不支持该db_type')
                    return
            return wrapper
        return inner
    @auth(type='file')
    def index(x, y):
        print('index->>%s:%s' % (x, y))
    
    @auth(type='mysql')
    def home(name):
        print('home->>%s' % name)
    
    @auth(type='ldap')
    def transfer():
        print('transfer')
    
    index(1, 2)
    home('egon')
    transfer()
    
    # 2:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作
    dic={}
    
    def makedic(name):
        def deco(func):
            dic[name]=func
        return deco
    @makedic('select')
    def func1():
        print('select')
    
    @makedic('update')
    def func2():
        print('update')
    
    print(dic)
    
    dic.get('select')()
    
    
    # 3、 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
    # 注意:时间格式的获取
    # import time
    # time.strftime('%Y-%m-%d %X')
    import time
    def inner(path):
        def decrp(func):
            def wrapper(*args, **kwargs):
                res = func(*args, **kwargs)
                with open(path, 'at', encoding='utf-8') as f:
                    f.write(f'{time.strftime("%Y-%m-%d %X")} {func.__name__} run
    ')
                return res
            return wrapper
        return decrp
    
    @inner('log.txt')
    def f1():
        print('start...')
    
    f1()
    
    # 4、基于迭代器的方式,用while循环迭代取值字符串、列表、元组、字典、集合、文件对象
    def func(obj):
        item = iter(obj)
        while 1:
            try:
                if isinstance(obj, dict):
                    print(obj[next(item)])
                else:
                    print(next(item))
            except StopIteration:
                break
        return
    
    l = ['name',"fyy", "age",17]
    
    func(l)
    
    # 5、自定义迭代器实现range功能
    def my_range(start,stop,step=1):
        while start < stop:
            yield start
            start+=step
    for i in my_range(1, 10, 2):
        print(i)
    
    
    ====================本周选做作业如下====================
    编写小说阅读程序实现下属功能
    # 一:程序运行开始时显示
        0 账号注册
        1 充值功能
        2 阅读小说
    
    
    # 二: 针对文件db.txt,内容格式为:"用户名:密码:金额",完成下述功能
    2.1、账号注册
    2.2、充值功能
    
    # 三:文件story_class.txt存放类别与小说文件路径,如下,读出来后可用eval反解出字典
    {"0":{"0":["倚天屠狗记.txt",3],"1":["沙雕英雄转.txt",10]},"1":{"0":["令人羞耻的爱.txt",6],"1":["二狗的妻子与大草原的故事.txt",5]},}
    
    3.1、用户登录成功后显示如下内容,根据用户选择,显示对应品类的小说编号、小说名字、以及小说的价格
    """
    0 玄幻武侠
    1 都市爱情
    2 高效养猪36技
    """
    
    3.2、用户输入具体的小说编号,提示是否付费,用户输入y确定后,扣费并显示小说内容,如果余额不足则提示余额不足
    
    # 四:为功能2.2、3.1、3.2编写认证功能装饰器,要求必须登录后才能执行操作
    
    # 五:为功能2.2、3.2编写记录日志的装饰器,日志格式为:"时间 用户名 操作(充值or消费) 金额"
    
    
    # 附加:
    # 可以拓展作者模块,作者可以上传自己的作品
    
    
    import os, time
    
    def islogin(func):
        def wrapper(*args, **kwargs):
            if usercookie:
                return func(*args, **kwargs)
            else:
                print("======>请先登录")
                login()
        return wrapper
    
    def nowtimer():
        return time.strftime('%Y-%m-%d %X')
    
    def log(msg, name, money):
        nowtime = nowtimer()
        with open(f'{name}.log', mode="at", encoding="utf-8") as f:
            f.write(f'{nowtime}  {name}  {msg}  {money}¥
    ')
        return
    
    def bookmsg():
        with open('book.txt', 'rt', encoding='utf-8') as f:
            data = f.read()
        dic = eval(data)
        return dic
    
    def changebookmsg(booktype, bookname, bookmoney):
        global bookdict
        dic = bookdict.get(booktype)
        dic[str(len(dic))] = [bookname, int(bookmoney)]
        bookdict[booktype] = dic
        with open('book.txt', 'wt', encoding='utf-8') as f:
            f.write(str(bookdict))
        return
    
    
    def checkuser(name):
        flag = 0
        userpwd = ""
        money = ''
        if os.path.exists("db.txt"):
            with open("db.txt", mode="rt", encoding="utf-8") as f:
                for line in f:
                    username, userpwd, money = line.strip().split(":")
                    if name == username:
                        flag = 1
                        break
        return flag, userpwd, money
    
    def changeusermsg(name, money):
        with open("db.txt", mode='rt', encoding="utf-8") as f, 
                open("db.txt.swap", mode="wt", encoding="utf-8") as ff:
            for line in f:
                uname, upwd, umoney = line.strip().split(":")
                if uname == name:
                    umoney = eval(umoney+money)
                    ff.write(f'{uname}:{upwd}:{umoney}
    ')
                else:
                    ff.write(f'{uname}:{upwd}:{umoney}
    ')
        os.remove("db.txt")
        os.rename("db.txt.swap", "db.txt")
        return
    
    def login():
        print("登录界面".center(50, '='))
        name = input("请输入账号:").strip()
        flag, userpwd, _ = checkuser(name)
        if flag:
            while 1:
                pwd = input("请输入密码:").strip()
                if pwd == userpwd:
                    global usercookie
                    usercookie = name
                    break
                else:
                    print("密码错误,请从新输入")
            print("登录成功,祝您阅读愉快!")
            return
        else:
            print("账号不存在,请先注册")
            return
    
    def regist():
        print("注册界面".center(50, '='))
        while 1:
            name = input("请输入账号:").strip()
            flag, *_ = checkuser(name)
            if not flag:
                break
            else:
                print("账号已存在")
        while 1:
            pwd = input("请输入密码:").strip()
            check_pwd = input("请确认密码:").strip()
            if check_pwd == pwd:
                break
            print("两次密码不一致")
        while 1:
            money = input("请输入账号金额:")
            if money.isdigit():
                break
            print("金额非法输入")
        with open("db.txt", mode="at", encoding="utf-8") as f:
            f.write(f'{name}:{pwd}:{money}
    ')
        print("注册成功".center(50, '='))
        return
    
    @islogin
    def recharge():
        print("充值".center(50, '='))
        while 1:
            wmoney = input("请输入存款金额:").strip()
            if not wmoney.isdigit():
                print("非法输入,请重新输入")
                continue
            break
        changeusermsg(usercookie, f'+{wmoney}')
        log("充值", usercookie, f'+{wmoney}')
        print("存款成功".center(50, '='))
        return
    
    
    @islogin
    def read():
        print("小说分类".center(50, '='))
        while 1:
            print(msg)
            cmd = input("输入指令(序号)>>>:").strip()
            if cmd in bookdict:
                readbook(cmd)
            else:
                print('无效指令,请重新输入')
    
    def readbook(cmd):
        print("小说列表".center(50, '='))
        booklist = bookdict.get(cmd)
        *_, money = checkuser(usercookie)
        while 1:
            for i in range(len(booklist)):
                print(f'{i}  {booklist.get(str(i))[0]}  {booklist.get(str(i))[1]}¥')
            cmd = input("请选择要阅读的小说>>>:")
            if not cmd.isdigit() or int(cmd) > len(booklist)-1:
                print("指令无效,请重新输入")
                continue
            isok = input("是否付费(y/n)>>>:")
            if isok.lower() == 'y':
                if int(money) < int(booklist.get(str(i))[1]):
                    print("余额不足")
                    continue
                changeusermsg(usercookie, f'-{booklist.get(str(i))[1]}')
                log('消费', usercookie, f'-{booklist.get(str(i))[1]}')
                print("付费成功,祝您阅读愉快!")
                return
    
    @islogin
    def uploadbook():
        print('书籍上传'.center(50, '='))
        while 1:
            print(msg)
            cmd = input('选择要上传的书籍的类型>>>:')
            if cmd in bookdict:
                while 1:
                    bookname = input("请输入书名:")
                    bookmoney = input('请输入书的价格:')
                    if not bookname and not bookmoney.isdigit():
                        print("非法输入,请重新输入")
                    changebookmsg(cmd, f'{bookname}.txt', bookmoney)
                    print("书籍上传成功".center(50, '='))
                    return
            else:
                print('无效指令,请重新输入')
    
    
    dic = {'0':regist,'1':recharge,'2':read,'3':uploadbook}
    
    usercookie = None
    
    msg = '''
        0 玄幻武侠
        1 都市爱情
        2 修真小说
    '''
    
    bookdict = bookmsg()
    
    if __name__ == '__main__':
        print("欢迎来到egon小说网".center(50, '='))
        while 1:
            print('''
        0 账号注册
        1 充值功能
        2 阅读小说
        3 上传书籍
                ''')
            cmd = input("输入指令(序号)>>>:").strip()
            if cmd in dic:
                dic[cmd]()
            else:
                print("无效命令")
    
    

    3月23号

    # 一:编写函数,(函数执行的时间用time.sleep(n)模拟)
    import time
    def index(x,y):
        start=time.time()
        time.sleep(3)
        print(f'index:{x,y}')
        stop = time.time()
        print(stop - start)
    
    # 二:编写装饰器,为函数加上统计时间的功能
    import time
    def time(func):
        def wrapper(*args, **kwargs):
            start = time.time()
            res = func(*args, **kwargs)
            stop = time.time()
            print(stop - start)
            return res
        return wrapper
    
    @time
    def index(x,y):
        time.sleep(3)
        print('index %s %s' %(x,y))
    
    res = index(1,2)
    
    
    # 三:编写装饰器,为函数加上认证的功能
    def auth(func):
        def wrapper(*args,**kwargs):
            name=input('your name>>: ').strip()
            pwd=input('your password>>: ').strip()
            if name == 'egon' and pwd == '123':
                res=func(*args,**kwargs)
                return res
            else:
                print('账号密码错误')
        return wrapper
    
    @auth
    def index():
        print('from index')
    
    index()
    
    # 四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
    # 注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
    userdb = "db.txt"
    login_status = {"user":None, "status":False}
    def auth(func):
        def wrapper(*args, **kwargs):
            if login_status["user"] and login_status["pwd"]:
                return func(*args, **kwargs)
            else:
                with open(userdb, mode="rt", encoding="utf-8") as f:
                    dic = eval(f.read())
                username = input('username: ').strip()
                userpwd = input('password: ').strip()
                if username in dic and userpwd == dic[username]:
                    login_status['user'] = username
                    login_status['status'] = True
                    res = func(*args, **kwargs)
                    return res
                else:
                    print('username or password error')
                    return
        return wrapper
    
    @auth
    def index():
        print('welcome')
    
    @auth
    def home(name):
        print(f'welcome to home {name}')
    
    index()
    home("tank")
    
    # 五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
    import time
    user={'user':None,'logintime':None,'timeout':10,}
    def auth(func):
        def wrapper(*args,**kwargs):
            if user['user']:
                timeout=time.time()-user['logintime']
                print(timeout)
                if timeout < user['timeout']:
                    return func(*args,**kwargs)
            name=input('username>>: ').strip()
            pwd=input('password>>: ').strip()
            if name == 'egon' and pwd == '123':
                user['user']=name
                user['logintime']=time.time()
                res=func(*args,**kwargs)
                return res
        return wrapper
    
    @auth
    def index():
        print('welcome')
        time.sleep(3)
    
    @auth
    def home(name):
        print(f'welcome to home {name}')
        time.sleep(9)
    
    index()
    home('egon')
    index()
    
    

    3月20号

    编写计数器功能,要求调用一次在原有的基础上加一
          温馨提示:
           	  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 couter():
        x = 0
        def add():
            nonlocal x
            n = x
            x += 1
            return n
        return add
    o = couter()
    print(o())
    print(o())
    print(o())
    
    # ====================周末作业====================
    # 编写ATM程序实现下述功能,数据来源于文件db.txt
    # 0、注册功能:用户输入账号名、密码、金额,按照固定的格式存入文件db.txt
    # 1、登录功能:用户名不存在,要求必须先注册,用户名存在&输错三次锁定,登录成功后记录下登录状态(提示:可以使用全局变量来记录)
    
    下述操作,要求登录后才能操作
    # 1、充值功能:用户输入充值钱数,db.txt中该账号钱数完成修改
    # 2、转账功能:用户A向用户B转账1000元,db.txt中完成用户A账号减钱,用户B账号加钱
    # 3、提现功能:用户输入提现金额,db.txt中该账号钱数减少
    # 4、查询余额功能:输入账号查询余额
    
    import os, time, datetime
    
    class Util:
        def inw(self):
            name = input("请输入账号:").strip()
            pwd = input("请输入密码:").strip()
            return name, pwd
    
        def checkuser(self, name):
            flag = 0
            userpwd = ""
            money = ''
            if os.path.exists("db.txt"):
                with open("db.txt", mode="rt", encoding="utf-8") as f:
                    for line in f:
                        username, userpwd, money = line.strip().split(":")
                        if name == username:
                            flag = 1
                            break
            return flag, userpwd, money
    
        def changeusermsg(self, name, money):
            with open("db.txt", mode='rt', encoding="utf-8") as f, 
                    open("db.txt.swap", mode="wt", encoding="utf-8") as ff:
                for line in f:
                    uname, upwd, umoney = line.strip().split(":")
                    if uname == name:
                        umoney = round(eval(umoney+money),2)
                        ff.write(f'{uname}:{upwd}:{umoney}
    ')
                    else:
                        ff.write(f'{uname}:{upwd}:{umoney}
    ')
            os.remove("db.txt")
            os.rename("db.txt.swap", "db.txt")
            return
    
        def nowtime(self):
            return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    
        def water(self, wstr, uname, money):
            nowtime = self.nowtime()
            with open(f'{uname}.log', mode="at", encoding="utf-8") as f:
                f.write(f'{nowtime}  {wstr}  {money}¥
    ')
            return
    
        def shopmsg(self, uname, shoplist, sum):
            shoptime = self.nowtime()
            with open(f'{uname}.shop', mode='at', encoding="utf-8") as f:
                f.write(f'{shoptime}
    ')
                for k, v in shoplist.items():
                    f.write(f'商品名:{dic_shop.get(k)[0]}  单价:{dic_shop.get(k)[1]}¥  数量:{v}
    ')
                f.write(f'总额:{sum}¥
    ')
            return
    
        def readwater_or_shopmsg(self, path):
            if os.path.exists(path):
                with open(path, mode="rt", encoding="utf-8") as f:
                    for line in f:
                        print(line, end="")
                return 1
            else:
                return 0
    
        def is_input_lgc(self, s, num):
            if num == 1:
                for i in s:
                    if not i.isalpha():
                        print("账号存在非法字符")
                        return 0
                if 2 < len(s) < 8:
                    return 1
                else:
                    print("非法账号")
                    return 0
            elif num == 2:
                if s.isdigit():
                    return 1
                else:
                    for i in s:
                        if i.isdigit() or i == '.':
                            continue
                        else:
                            return 0
                    if s.count('.') == 1 and len(s[s.find('.') + 1:]) <= 2:
                        return 1
                    else:
                        return 0
            else:
                for i in s:
                    if i.isspace():
                        print("密码中存在空格")
                        return 0
                return 1
    class Lock:
        def locked(self, name):
            locktime = str(time.time())
            with open("lock.txt", mode="at", encoding="utf-8") as f:
                f.write(f'{name}:{locktime}
    ')
    
        def checklock(self, name):
            flag = 0
            if os.path.exists('lock.txt'):
                with open("lock.txt", mode="rt", encoding="utf-8") as f:
                    for i in f:
                        username, _= i.strip().split(":")
                        if username == name:
                            flag =1
            return flag
    
        def unlock(self, name):
            with open("lock.txt", mode="rt", encoding="utf-8") as f:
                for line in f:
                    username, locktime = line.strip().split(":")
                    if username == name:
                        break
            curtime = datetime.datetime.now()
            lock_time = datetime.datetime.fromtimestamp(float(locktime))
            difftime = (curtime - lock_time).seconds
            if difftime < 60:
                return 60 - int(difftime)
            else:
                with open("lock.txt", mode="rt", encoding="utf-8") as f,
                        open("lock.txt.swap", mode="wt", encoding="utf-8") as ff:
                    for i in f:
                        username, locktime = i.split(":")
                        if username == name:
                            continue
                        else:
                            ff.write(f'{username}:{locktime}')
                os.remove("lock.txt")
                os.rename('lock.txt.swap', 'lock.txt')
                return 0
    
    class Atm(Util):
        def view_account(self):
            '''查看余额'''
            print(f"{cookie}的余额".center(50, '='))
            with open("users.txt", mode="rt", encoding="utf-8") as f:
                for line in f:
                    username, _, money = line.strip().split(":")
                    if username == cookie:
                        print(f"余额:{money}¥")
                        break
            return
    
        def transfer_accounts(self):
            '''转账'''
            print('转账'.center(50, '='))
            tname = input("请输入要转账的账号:").strip()
            flag, *_ = self.checkuser(tname)
            *_, money = self.checkuser(cookie)
            if flag:
                while 1:
                    tmoney = input("请输入转账金额:").strip()
                    if not self.is_input_lgc(tmoney, 2):
                        print("非法输入,请重新输入")
                        continue
                    else:
                        m = float(money) - float(tmoney)
                        if m < 0:
                            print("账号余额不足, 无法转账")
                            continue
                    break
                self.changeusermsg(cookie, f'-{tmoney}')
                time.sleep(1)
                self.changeusermsg(tname, f'+{tmoney}')
                print("转账成功".center(50, '='))
                self.water(f"转账({tname})", cookie, f'-{tmoney}')
                self.water(f"({cookie})转账", tname, f'+{tmoney}')
                return
            else:
                print("转账账号不存在")
                return
    
        def withdrawal(self):
            '''存款'''
            print("存款".center(50, '='))
            while 1:
                wmoney = input("请输入存款金额:").strip()
                if not self.is_input_lgc(wmoney, 2):
                    print("非法输入,请重新输入")
                    continue
                break
            self.changeusermsg(cookie, f'+{wmoney}')
            print("存款成功".center(50, '='))
            self.water("存款", cookie, f'+{wmoney}')
            return
    
        def deposit(self):
            '''取款'''
            print("取款".center(50, '='))
            *_, money = self.checkuser(cookie)
            while 1:
                dmoney = input("请输入取款金额:").strip()
                if not self.is_input_lgc(dmoney, 2):
                    print("非法输入,请重新输入")
                    continue
                if float(money) < float(dmoney):
                    print("余额不足")
                    continue
                break
            self.changeusermsg(cookie, f'-{dmoney}')
            print("取款成功".center(50, '='))
            self.water("取款", cookie, f'-{dmoney}')
            return
    
        def check_water(self):
            '''查看流水'''
            print(f'{cookie}的流水'.center(50, '='))
            flag = self.readwater_or_shopmsg(f'{cookie}.log')
            if not flag:
                print("您没有流水可以查看")
                return
            return
    
    class Shop(Util):
        def shopping(self):
            '''购物'''
            print("购物".center(50, '='))
            for k, v in dic_shop.items():
                print(f'  {k}. {v[0]}  {v[1]}¥')
            print(f'  (购物请输入商品序号, 结算请输入Y / y)')
            sum = 0
            shop_car = {}
            while 1:
                shopcmd = input("请输入命令(序号)>>>:")
                if shopcmd.upper() == "Y":
                    for k, v in shop_car.items():
                        sum += dic_shop.get(k)[1] * int(v)
                    *_, money = self.checkuser(cookie)
                    if float(money) >= sum:
                        self.changeusermsg(cookie, f'-{sum}')
                        self.water("购物", cookie, f'-{sum}')
                        print("购物成功".center(50, '='))
                        self.shopmsg(cookie, shop_car, sum)
                        return
                    else:
                        print("账号余额不足,购物失败")
                        return
                if shopcmd in dic_shop:
                    shopcount = input("请输入购买数量:")
                    shop_car[shopcmd] = shopcount
                else:
                    print("无效指令,请重新输入")
    
        def check_shop(self):
            '''查看购买商品'''
            print(f'{cookie}的购物历史'.center(50, '='))
            flag = self.readwater_or_shopmsg(f'{cookie}.shop')
            if not flag:
                print("您还没有购物历史哦!")
                return
            return
    
    class User(Atm, Shop, Util, Lock):
        def login(self):
            print("登录界面".center(50, '='))
            name, pwd = self.inw()
            flag, userpwd, _ = self.checkuser(name)
            if flag:
                if self.checklock(name):
                    res = self.unlock(name)
                    if res:
                        print(f'账号{res}秒后解锁')
                        return
                count = 0
                while 1:
                    if pwd == userpwd:
                        global cookie
                        cookie = name
                        print(f"欢迎您{name}".center(50, '='))
                        print(msg1)
                        cmd = input("请输入命令(序号)>>>:")
                        if not cmd.isdigit() or int(cmd) > 7:
                            print("命令无效,请重新输入")
                            continue
                        if cmd == "0":
                            self.exit()
                            return
                        else:
                           self.__getattribute__(dic.get(str(int(cmd)+2))[0])()
                    else:
                        count += 1
                        if count == 3:
                            self.locked(name)
                            print("账号输入次数过多,锁定1分钟")
                            return
                        print("密码错误,请从新输入")
                        pwd = input("请输入密码:")
            else:
                print("账号不存在,请先注册")
                return
    
        def regist(self):
            print("注册界面".center(50, '='))
            print(msg2)
            while 1:
                name = input("请输入账号:").strip()
                if self.is_input_lgc(name, 1):
                    flag, *_ = self.checkuser(name)
                    if not flag:
                        break
                    else:
                        print("账号已存在")
            while 1:
                pwd = input("请输入密码:").strip()
                if not self.is_input_lgc(pwd, 3):
                    continue
                if len(pwd) < 4:
                    print("密码长度小于4")
                    continue
                check_pwd = input("请确认密码:").strip()
                if check_pwd == pwd:
                    break
                print("两次密码不一致")
    
            while 1:
                money = input("请输入账号金额:").strip()
                if self.is_input_lgc(money, 2):
                    break
                print("金额非法输入,请重新注册")
    
            with open("db.txt", mode="at", encoding="utf-8") as f:
                f.write(f'{name}:{pwd}:{money}
    ')
            print("注册成功".center(50, '='))
            return
    
        def exit(self):
            global cookie
            cookie = ''
    
    cookie = ''
    dic = {'0':('exit','退出'),'1':('login','登录'), '2':('regist','注册'),
           '3':('view_account','查看余额'), '4':('transfer_accounts','转账'),'5':('withdrawal','存款'),
           '6':('deposit','取款'), '7':('check_water','查看流水'),'8':('shopping','购物'),
           '9':('check_shop','查看购买商品')
    }
    
    dic_shop = {
        '1':("thinkpad",8888),
        '2':("小黄书",100),
        '3':("iphone",5500),
        '4':("辣条",2.5),
        '5':("衣服",199),
        '6':("水果",38.8),
    }
    msg1 = '''
        0.退出
        1.查看余额
        2.转账
        3.存款
        4.取款
        5.查看流水
        6.购物
        7.查看购买商品
    '''
    msg2 = '''
        欢迎注册001ATM机账号!注意注册账号请满足以下规则。
        1.账号必须由字母组成,长度大于2小于8
        2.密码中不允许有空格,长度大于等于4
        3.账号金额必须是整数或小数(小数点后只允许2位)
        '''
    
    if __name__ == '__main__':
        print("欢迎使用001ATM机!".center(50, '='))
        while 1:
            for i in range(1, 3):
                print(f'  {i}. {dic.get(str(i))[1]}')
            cmd = input("输入指令(序号)>>>:").strip()
            if cmd in dic:
                if cmd == '1' or cmd == '2':
                    o = User()
                    res = o.__getattribute__(dic.get(cmd)[0])
                    res()
                else:
                    print("======>请先登录")
                    continue
            else:
                print("无效命令")
    
    

    3月19号

    # 1、如下全局变量记录了当前登录用户,编写登录功能,一旦用户登录成功,则将全局变量赋值为当前登录的用户名
    login_user=None
    username = "egon"
    userpwd = "root"
    name = input("请输入账号:").strip()
    pwd = input("请输入密码:").strip()
    if name == username and pwd == userpwd:
        login_user = username
        print(f"欢迎您{name}".center(30, '='))
    else:
        print("密码或账号错误")
    

    3月18号

    # 1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成修改操作
    def modifyfile(path, oldstr, newstr):
        with open(path, mode='rt', encoding='utf-8') as f:
            data = f.read()
        with open(path, mode='wt', encoding='utf-8') as f:
            f.write(data.replace(oldstr,newstr))
            
    # 2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
    def foo(string):
        dic = {"num":0, "alph":0, "space":0, "other":0}
        for i in string:
            if i.isdigit():
                dic["num"] += 1
            elif i.isalpha():
                dic["alph"] += 1
            elif i.isspace():
                dic["space"] += 1
            else:
                dic["other"] += 1
        return dic
    print(foo("qw 34 5 tvASKZ&*% 1234"))
    
    # 3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
    def foo(obj):
        if len(obj) > 5:
            return True
        return False
    print(foo((1,2,3,4,5,6)))
    print(foo({"a":1,"b":3,"c":2,"d":1,"e":0}))
    print(foo([1,2,3,4]))
    
    # 4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
    def foo(li):
        if len(li) > 2:
            return li[:2]
        return False
    res = foo([2,6,1,8])
    print(res)
    
    # 5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
    def foo(obj):
        return obj[1::2]
    res = foo((3,7,0,1,4,8,2))
    print(res)
    
    # 6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
    PS:字典中的value只能是字符串或列表
    dic = {"k1": "v1v1", "k2": [11,22,33,44]}
    def foo(dic):
        for k, v in dic.items():
            if len(v) > 2:
                dic[k] = v[:2]
        return dic
    res = foo(dic)
    print(res)
    
    

    3月17号

    # 1、编写文件修改功能,调用函数时,传入三个参数(修改的文件路径,要修改的内容,修改后的内容)既可完成文件的修改
    def modifyfile(path, oldstr, newstr):
        with open(path, mode='rt', encoding='utf-8') as f:
            data = f.read()
        with open(path, mode='wt', encoding='utf-8') as f:
            f.write(data.replace(oldstr,newstr))
    
    # 2、编写tail工具
    import time
    def tail(path):
        with open(path, mode="rb") as f:
            f.seek(0,2)
            while 1:
                line = f.readline()
                if len(line) == 0:
                    time.sleep(1)
                else:
                    print(line.decode("utf-8"), end="")
    
    
    # 3、编写登录功能
    # 4、编写注册功能
    # 5、编写用户认证功能
    import os, sys, time, datetime
    class Lock:
        def locked(self, name):
            locktime = str(time.time())
            with open("lock.txt", mode="at", encoding="utf-8") as f:
                f.write(f'{name}:{locktime}
    ')
    
        def checklock(self, name):
            flag = 0
            if os.path.exists('lock.txt'):
                with open("lock.txt", mode="rt", encoding="utf-8") as f:
                    for i in f:
                        username, _= i.strip().split(":")
                        if username == name:
                            flag =1
            return flag
    
        def unlock(self, name):
            with open("lock.txt", mode="rt", encoding="utf-8") as f:
                for line in f:
                    username, locktime = line.strip().split(":")
                    if username == name:
                        break
            curtime = datetime.datetime.now()
            lock_time = datetime.datetime.fromtimestamp(float(locktime))
            difftime = (curtime - lock_time).seconds
            if difftime < 30:
                return 30 - int(difftime)
            else:
                with open("lock.txt", mode="rt", encoding="utf-8") as f,
                        open("lock.txt.swap", mode="wt", encoding="utf-8") as ff:
                    for i in f:
                        username, locktime = i.split(":")
                        if username == name:
                            continue
                        else:
                            ff.write(f'{username}:{locktime}')
                os.remove("lock.txt")
                os.rename('lock.txt.swap', 'lock.txt')
                return 0
    
    class User(Lock):
    
        def __init__(self, name, pwd):
            self.name = name
            self.pwd = pwd
    
        def login(self):
            flag, userpwd = self.checkname()
            if flag:
                islogin = 0
                if userpwd == self.pwd:
                    islogin = 1
                if islogin:
                    return 1
                else:
                    return 0
            else:
                return 3
    
        def regist(self):
            flag, _ = self.checkname()
            if not flag:
                with open("user.txt", mode="at", encoding="utf-8") as f:
                    f.write(f'{name}:{pwd}
    ')
                return 1
            else:
                return 0
    
        def checkname(self):
            flag = 0
            userpwd = ""
            if os.path.exists('user.txt'):
                with open("user.txt", mode="rt", encoding="utf-8") as f:
                    for line in f:
                        username, userpwd = line.strip().split(":")
                        if self.name == username:
                            flag = 1
                            break
            return flag, userpwd
    
    def inw():
        name = input("请输入账号:").strip()
        pwd = input("请输入密码:").strip()
        return name, pwd
    
    if __name__ == '__main__':
        usercount = {}
        while 1:
            print("""
        0.退出
        1.登录
        2.注册
            """)
            cmd = input("请输入命令编号>>::")
            if not cmd.isdigit():
                print('必须输入命令编号的数字,傻叉')
                continue
            if cmd == "0":
                sys.exit()
            elif cmd == "1":
                print("欢迎登录")
                count = 0
                while 1:
                    name, pwd = inw()
                    o = User(name, pwd)
                    flag = o.checklock(name)
                    if flag and o.unlock(name):
                        res = o.unlock(name)
                        print(f'账号{res}秒后解锁')
                        break
                    else:
                        if name not in usercount:
                            usercount[name] = 0
                        t = o.login()
                        if t == 1:
                            print("登录成功")
                            print(f'欢迎您{name}')
                            usercount[name] = 0
                            break
                        elif t== 0:
                            print("账号密码错误")
                            usercount[name] += 1
                            if usercount.get(name) == 3:
                                print("账号输错次数过多锁定30秒")
                                o.locked(name)
                                usercount[name] = 0
                                break
                            continue
                        else:
                            print("账号不存在,请先注册")
                            break
            elif cmd == "2":
                print("欢迎注册")
                while 1:
                    name, pwd = inw()
                    o = User(name, pwd)
                    flag = o.regist()
                    if flag:
                        print("注册成功")
                        break
                    else:
                        print("账号已存在,请从新注册")
            else:
                print("输入的命令不存在")
    
    # 选做题:编写ATM程序实现下述功能,数据来源于文件db.txt
    # 1、充值功能:用户输入充值钱数,db.txt中该账号钱数完成修改
    # 2、转账功能:用户A向用户B转账1000元,db.txt中完成用户A账号减钱,用户B账号加钱
    # 3、提现功能:用户输入提现金额,db.txt中该账号钱数减少
    # 4、查询余额功能:输入账号查询余额
    # 选做题中的选做题:登录功能
    # 用户登录成功后,内存中记录下该状态,上述功能以当前登录状态为准,必须先登录才能操作
    import os, time
    
    class Util:
        def inw(self):
            name = input("请输入账号:").strip()
            pwd = input("请输入密码:").strip()
            return name, pwd
    
        def checkuser(self, name):
            flag = 0
            userpwd = ""
            money = ''
            if os.path.exists("users.txt"):
                with open("users.txt", mode="rt", encoding="utf-8") as f:
                    for line in f:
                        username, userpwd, money = line.strip().split(":")
                        if name == username:
                            flag = 1
                            break
            return flag, userpwd, money
    
        def changeusermsg(self, name, money):
            with open("users.txt", mode='rt', encoding="utf-8") as f, 
                    open("users.txt.swap", mode="wt", encoding="utf-8") as ff:
                for line in f:
                    uname, upwd, umoney = line.strip().split(":")
                    if uname == name:
                        umoney = round(eval(umoney+money),2)
                        ff.write(f'{uname}:{upwd}:{umoney}
    ')
                    else:
                        ff.write(f'{uname}:{upwd}:{umoney}
    ')
            os.remove("users.txt")
            os.rename("users.txt.swap", "users.txt")
    
        def nowtime(self):
            return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    
        def water(self, wstr, uname, money):
            nowtime = self.nowtime()
            with open(f'{uname}.log', mode="at", encoding="utf-8") as f:
                f.write(f'{nowtime}  {wstr}  {money}
    ')
    
        def shopmsg(self, uname, shoplist, sum):
            shoptime = self.nowtime()
            with open(f'{uname}.shop', mode='at', encoding="utf-8") as f:
                f.write(f'{shoptime}
    ')
                for k, v in shoplist.items():
                    f.write(f'商品名:{k}  单价:{dic_shop.get(k)}¥  数量:{v}
    ')
                f.write(f'总额:{sum}¥
    ')
    
        def readwater_or_shopmsg(self, path):
            if os.path.exists(path):
                with open(path, mode="rt", encoding="utf-8") as f:
                    for line in f:
                        print(line, end="")
                return 1
            else:
                return 0
    
    class Atm(Util):
        def view_account(self):
            '''查看余额'''
            print(f"{cookie}的余额".center(50, '='))
            with open("users.txt", mode="rt", encoding="utf-8") as f:
                for line in f:
                    username, _, money = line.strip().split(":")
                    if username == cookie:
                        print(f"余额:{money}¥")
                        break
            return
    
        def transfer_accounts(self):
            '''转账'''
            print('转账'.center(50, '='))
            tname = input("请输入要转账的账号:").strip()
            flag, *_ = self.checkuser(tname)
            *_, money = self.checkuser(cookie)
            if flag:
                while 1:
                    tmoney = input("请输入转账金额:").strip()
                    if not tmoney.isdigit():
                        print("非法输入,请重新输入")
                        continue
                    else:
                        m = float(money) - float(tmoney)
                        if m < 0:
                            print("账号余额不足, 无法转账")
                            continue
                    break
                self.changeusermsg(cookie, f'-{tmoney}')
                time.sleep(1)
                self.changeusermsg(tname, f'+{tmoney}')
                print("转账成功".center(50, '='))
                self.water("转账", cookie, f'-{tmoney}')
                self.water("转账", tname, f'+{tmoney}')
                return
            else:
                print("转账账号不存在")
                return
    
        def withdrawal(self):
            '''存款'''
            print("存款".center(50, '='))
            while 1:
                wmoney = input("请输入存款金额:").strip()
                if not wmoney.isdigit():
                    print("非法输入,请重新输入")
                    continue
                break
            self.changeusermsg(cookie, f'+{wmoney}')
            print("存款成功".center(50, '='))
            self.water("存款", cookie, f'+{wmoney}')
            return
    
        def deposit(self):
            '''取款'''
            print("取款".center(50, '='))
            *_, money = self.checkuser(cookie)
            while 1:
                dmoney = input("请输入取款金额:").strip()
                if not dmoney.isdigit():
                    print("非法输入,请重新输入")
                    continue
                if float(money) < float(dmoney):
                    print("余额不足")
                    continue
                break
            self.changeusermsg(cookie, f'-{dmoney}')
            print("取款成功".center(50, '='))
            self.water("取款", cookie, f'-{dmoney}')
            return
    
        def check_water(self):
            '''查看流水'''
            print(f'{cookie}的流水'.center(50, '='))
            flag = self.readwater_or_shopmsg(f'{cookie}.log')
            if not flag:
                print("您没有流水可以查看")
                return
            return
    
    class Shop(Util):
        def shopping(self):
            '''购物'''
            print("购物".center(50, '='))
            sum = 0
            shop_car = {}
            print(msg_shop)
            while 1:
                shopcmd = input("请输入命令(序号)>>>:")
                if shopcmd.upper() == "Y":
                    for k, v in shop_car.items():
                        sum += dic_shop.get(k) * int(v)
                    *_, money = self.checkuser(cookie)
                    if float(money) >= sum:
                        self.changeusermsg(cookie, f'-{sum}')
                        self.water("购物", cookie, f'-{sum}')
                        print("购物成功".center(50, '='))
                        self.shopmsg(cookie, shop_car, sum)
                        return
                    else:
                        print("账号余额不足,购物失败")
                        return
                if shoplist[int(shopcmd)] in dic_shop:
                    shopcount = input("请输入购买数量:")
                    shop_car[shoplist[int(shopcmd)]] = shopcount
                else:
                    print("无效指令,请重新输入")
    
        def check_shop(self):
            '''查看购买商品'''
            print(f'{cookie}的购物历史'.center(50, '='))
            flag = self.readwater_or_shopmsg(f'{cookie}.shop')
            if not flag:
                print("您还没有购物历史哦!")
                return
            return
    
    class User(Atm, Shop, Util):
        def login(self):
            print("登录界面".center(50, '='))
            name, pwd = self.inw()
            flag, userpwd, _ = self.checkuser(name)
            if flag:
                while 1:
                    if pwd == userpwd:
                        global cookie
                        cookie = name
                        print(f"欢迎您{name}".center(50, '='))
                        print(msg1)
                        cmd = input("请输入命令(序号)>>>:")
                        if not cmd.isdigit() or int(cmd) > 7:
                            print("命令无效,请重新输入")
                            continue
                        if cmd == "0":
                            self.exit()
                            return
                        else:
                           self.__getattribute__(dic.get(str(int(cmd)+2)))()
                    else:
                        print("密码错误,请从新输入")
                        pwd = input("请输入密码:")
            else:
                print("账号不存在,请先注册")
                return
    
        def regist(self):
            print("注册界面".center(50, '='))
            while 1:
                name, pwd = self.inw()
                flag, *_ = self.checkuser(name)
                if not flag:
                    with open("users.txt", mode="at", encoding="utf-8") as f:
                        f.write(f'{name}:{pwd}:0
    ')
                    print("注册成功".center(50, '='))
                    return
                else:
                    print("账号以存在,请从新注册")
    
        def exit(self):
            global cookie
            cookie = ''
    
    cookie = ''
    dic = {'0':'exit', '1':'login', '2':'regist', '3':'view_account', '4':'transfer_accounts',
           '5':'withdrawal', '6':'deposit', '7':'check_water', '8':'shopping', '9':'check_shop'}
    dic_shop = {
        "thinkpad":8888,
        "小黄书":100,
        "iphone":5500,
        "辣条":2.5,
        "衣服":199,
        "水果":38.8
    }
    shoplist = ['','thinkpad','小黄书','iphone','辣条','衣服','水果']
    msg = '''
        1.登录
        2.注册
    '''
    msg1 = '''
        0.退出
        1.查看余额
        2.转账
        3.存款
        4.取款
        5.查看流水
        6.购物
        7.查看购买商品
    '''
    msg_shop = '''
        1. thinkpad 8888¥
        2. 小黄书 100¥
        3. iphone 5500¥
        4. 辣条 2.5¥
        5. 衣服 199¥
        6. 水果 38.8¥
        (购物请输入商品序号,结算请输入Y/y)
    '''
    if __name__ == '__main__':
        print("欢迎使用001ATM机!".center(50, '='))
        while 1:
            print(msg)
            cmd = input("输入指令(序号)>>>:").strip()
            if cmd in dic:
                if cmd == '1' or cmd == '2':
                    o = User()
                    res = o.__getattribute__(dic.get(cmd))
                    res()
                else:
                    print("---->请先登录")
                    continue
            else:
                print("无效命令")
    

    3月16号

    #1、通用文件copy工具实现
    file_path = input("输入源文件路径:")
    scp_path = input("输入拷贝路径:")
    with open(f'{file_path}', mode="rb") as f,
        open(f'{scp_path}', mode="wb") as ff:
        for line in f:
            ff.write(line)
    
    '''
    #a.txt
    aaaaegon
    略略略
    bbcc
    '''
    #2、基于seek控制指针移动,测试r+、w+、a+模式下的读写内容
    with open("a.txt", mode="r+t", encoding="utf-8") as f: # r+模式打开文件,文件不存在报错。文件指针指向开头
        print("----read-----")
        print(f.read())
        f.seek(0,0)
        f.write("啦啦啦")
        print("----write---")
        print(f.read())
        f.seek(0,0)
        print("----res---")
        print(f.read())
    '''
    ----read-----
    aaaaegon
    略略略
    bbcc
    ----write---
    
    略略略
    bbcc
    ----res---
    啦啦啦  #写操作直接覆盖
    略略略
    bbcc
    '''
    
    with open('a.txt', mode='w+b') as f: #w+模式打开文件,文件不存在创建。文件存在,清空文件。文件指针指向开头
        print('---read---')
        print(f.read().decode('utf-8'))
        f.write("tank".encode('utf-8'))
        print('-----write----')
        print(f.read().decode('utf-8'))
        f.seek(0,0)
        print('---res---')
        print(f.read().decode('utf-8'))
    '''
    ---read---
    
    -----write----
    
    ---res---
    tank
    '''
    
    with open('a.txt', mode='a+b') as f: #a+模式打开文件,文件不存在创建。文件指针指向结尾
        print('---read---')
        print(f.read().decode('utf-8'))
        f.seek(-10,2)
        print(f.tell())
        f.write("tank".encode('utf-8'))
        print('-----write----')
        print(f.read().decode('utf-8'))
        f.seek(0,0)
        print('---res---')
        print(f.read().decode('utf-8'))
    '''
    ---read---
    
    13 
    -----write----
    
    ---res---
    aaaaegon
    略略略
    bbcctank 
    '''
    
    #3、tail -f access.log程序实现
    ##读
    import time
    with open('access.log',mode='rb') as f:
        f.seek(0,2)
        while True:
            line=f.readline()
            if len(line) == 0:
                time.sleep(0.5)
            else:
                print(line.decode('utf-8'),end='')
    ##写
    with open("access.log", mode="at", encoding="utf-8") as f:
        f.write("lalalala")
    

    周末作业

    #周末综合作业:
    # 1:编写用户登录接口
    # #1、输入账号密码完成验证,验证通过后输出"登录成功"
    # #2、可以登录不同的用户
    # #3、同一账号输错三次锁定,(提示:锁定的用户存入文件中,这样才能保证程序关闭后,该用户仍然被锁定)
    
    # 2:编写程序实现用户注册后,可以登录,
    # 提示:
    # while True:
    #     msg = """
    #     0 退出
    #     1 登录
    #     2 注册
    #     """
    #     print(msg)
    #     cmd = input('请输入命令编号>>: ').strip()
    #     if not cmd.isdigit():
    #         print('必须输入命令编号的数字,傻叉')
    #         continue
    #
    #     if cmd == '0':
    #         break
    #     elif cmd == '1':
    #         # 登录功能代码(附加:可以把之前的循环嵌套,三次输错退出引入过来)
    #         pass
    #     elif cmd == '2':
    #         # 注册功能代码
    #         pass
    #     else:
    #         print('输入的命令不存在')
    #
    #     # 思考:上述这个if分支的功能否使用其他更为优美地方式实现
    
    import os, sys, time, datetime
    class Lock:
        def locked(self, name):
            locktime = str(time.time())
            with open("lock.txt", mode="at", encoding="utf-8") as f:
                f.write(f'{name}:{locktime}
    ')
    
        def checklock(self, name):
            flag = 0
            if os.path.exists('lock.txt'):
                with open("lock.txt", mode="rt", encoding="utf-8") as f:
                    for i in f:
                        username, _= i.strip().split(":")
                        if username == name:
                            flag =1
            return flag
    
        def unlock(self, name):
            with open("lock.txt", mode="rt", encoding="utf-8") as f:
                for line in f:
                    username, locktime = line.strip().split(":")
                    if username == name:
                        break
            curtime = datetime.datetime.now()
            lock_time = datetime.datetime.fromtimestamp(float(locktime))
            difftime = (curtime - lock_time).seconds
            if difftime < 30:
                return 30 - int(difftime)
            else:
                with open("lock.txt", mode="rt", encoding="utf-8") as f,
                        open("lock.txt.swap", mode="wt", encoding="utf-8") as ff:
                    for i in f:
                        username, locktime = i.split(":")
                        if username == name:
                            continue
                        else:
                            ff.write(f'{username}:{locktime}')
                os.remove("lock.txt")
                os.rename('lock.txt.swap', 'lock.txt')
                return 0
    
    class User(Lock):
    
        def __init__(self, name, pwd):
            self.name = name
            self.pwd = pwd
    
        def login(self):
            flag, userpwd = self.checkname()
            if flag:
                islogin = 0
                if userpwd == self.pwd:
                    islogin = 1
                if islogin:
                    return 1
                else:
                    return 0
            else:
                return 3
    
        def regist(self):
            flag, _ = self.checkname()
            if not flag:
                with open("user.txt", mode="at", encoding="utf-8") as f:
                    f.write(f'{name}:{pwd}
    ')
                return 1
            else:
                return 0
    
        def checkname(self):
            flag = 0
            userpwd = ""
            if os.path.exists('user.txt'):
                with open("user.txt", mode="rt", encoding="utf-8") as f:
                    for line in f:
                        username, userpwd = line.strip().split(":")
                        if self.name == username:
                            flag = 1
                            break
            return flag, userpwd
    
    def inw():
        name = input("请输入账号:").strip()
        pwd = input("请输入密码:").strip()
        return name, pwd
    
    if __name__ == '__main__':
        usercount = {}
        while 1:
            print("""
        0.退出
        1.登录
        2.注册
            """)
            cmd = input("请输入命令编号>>::")
            if not cmd.isdigit():
                print('必须输入命令编号的数字,傻叉')
                continue
            if cmd == "0":
                sys.exit()
            elif cmd == "1":
                print("欢迎登录")
                count = 0
                while 1:
                    name, pwd = inw()
                    o = User(name, pwd)
                    flag = o.checklock(name)
                    if flag and o.unlock(name):
                        res = o.unlock(name)
                        print(f'账号{res}秒后解锁')
                        break
                    else:
                        if name not in usercount:
                            usercount[name] = 0
                        t = o.login()
                        if t == 1:
                            print("登录成功")
                            print(f'欢迎您{name}')
                            usercount[name] = 0
                            break
                        elif t== 0:
                            print("账号密码错误")
                            usercount[name] += 1
                            if usercount.get(name) == 3:
                                print("账号输错次数过多锁定30秒")
                                o.locked(name)
                                usercount[name] = 0
                                break
                            continue
                        else:
                            print("账号不存在,请先注册")
                            break
            elif cmd == "2":
                print("欢迎注册")
                while 1:
                    name, pwd = inw()
                    o = User(name, pwd)
                    flag = o.regist()
                    if flag:
                        print("注册成功")
                        break
                    else:
                        print("账号已存在,请从新注册")
            else:
                print("输入的命令不存在")
    

    3月13号

    #1、编写文件copy工具
    sur = input("输入要copy的文件路径:").strip()
    cfile = input("输入要copy到哪里:").strip()
    with open(f'{sur}', mode="rt", encoding="utf-8") as f1,
            open(f'{cfile}', mode="wt", encoding="utf-8") as f2:
        res = f1.read()
        f2.write(res)
    #2、编写登录程序,账号密码来自于文件
    '''
    #user.txt
    egon:123
    tank:123
    '''
    name = input("请输入账号:").strip()
    pwd = input("请输入密码:").strip()
    with open("user.txt", mode="rt", encoding="utf-8") as f:
        for i in f:
            username, userpwd = i.strip().split(":")
            if username == name and pwd == userpwd:
                print("登录成功")
                break
        else:
            print("账号或密码错误")
    
    #3、编写注册程序,账号密码来存入文件
    name = input("输入账号:").strip()
    pwd = input("输入密码:").strip()
    with open("user.txt", mode="at", encoding="utf-8") as f:
        f.write(f'{name}:{pwd}
    ')
    

    3月11号

    # 1、有列表['alex',49,[1900,3,18]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量
    #
    li = ['alex',49,[1900,3,18]]
    name, age, birth = li
    year, month, data = birth
    print(name, age, year, month, data)
    
    # 2、用列表的insert与pop方法模拟队列
    #
    li = []
    while 1:
        print("""
        1.insert
        2.pop
        3.show
        4.exit
        """)
        sel = input("输入命令:").strip()
        if sel == "1":
            v = input("请输入插入的值:")
            li.insert(len(li),v)
        elif sel == "2":
            if len(li) == 0:
                print("队列为空")
            else:
                print(li.pop(0))
        elif sel == "3":
            print(li)
        else:
            break
    
    # 3. 用列表的insert与pop方法模拟堆栈
    #
    li = []
    while 1:
        print("""
        1.insert
        2.pop
        3.show
        4.exit
        """)
        sel = input("输入命令:").strip()
        if sel == "1":
            v = input("请输入插入的值:")
            li.insert(len(li), v)
        elif sel == "2":
            if len(li) == 0:
                print("栈为空")
            else:
                print(li.pop())
        elif sel == "3":
            print(li)
        else:
            break
    
    # 4、简单购物车,要求如下:
    # 实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数以三元组形式加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  
    msg_dic={
    'apple':10,
    'tesla':100000,
    'mac':3000,
    'lenovo':30000,
    'chicken':10,
    }
    shop_car = []
    while 1:
        for k, v in msg_dic.items():
            print(f'{k}: {v}')
        shopname = input("请输入购买的商品名:").strip().lower()
        shopcount = input("请输入购买个数:").strip()
        if shopcount.isdigit() and shopname in msg_dic:
            shopcount = int(shopcount)
        else:
            print("非法输入,请重新输入")
            continue
        shop = (shopname,msg_dic.get(shopname),shopcount)
        shop_car.append(shop)
        print(shop_car)
    
    # 5、有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中
    # 即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
    ll = [11,22,33,44,55,66,77,88,99,90]
    low = [x for x in ll if x < 66]
    heigh = [x for x in ll if x > 66]
    dic = dict(k1=heigh, k2=low)
    print(dic)
    
    #
    # 6、统计s='hello alex alex say hello sb sb'中每个单词的个数
    s = 'hello alex alex say hello sb sb'
    ss = set(s)
    dic = {}
    for i in ss:
        dic[i] = s.count(i)
    dic.pop(' ')
    print(dic)
    
    

    3月10号

    # 一:for循环
    # 1.1 for循环嵌套之打印99乘法表
    for i in range(1, 10):
        for j in range(1, i+1):
            print('{}x{}={}	'.format(j, i, i*j), end='')
        print()
    
    # 1.2 for循环嵌套之打印金字塔
    ##提示分析如下
    '''
    
                 #max_level=5
        *        #current_level=1,空格数=4,*号数=1
       ***       #current_level=2,空格数=3,*号数=3
      *****      #current_level=3,空格数=2,*号数=5
     *******     #current_level=4,空格数=1,*号数=7
    *********    #current_level=5,空格数=0,*号数=9
    
    #数学表达式
    空格数=max_level-current_level
    *号数=2*current_level-1
    '''
    num = 5
    for i in range(1, num+1):
        print(' ' * (num - i) + '*' * (2 * i - 1))
    
    
    # 1.3 用for+range改写今日早晨默写的代码,作为明天默写内容
    username='egon'
    password='root'
    for i in range(3):
        name = input('请输入您的账号:').strip()
        pwd = input('请输入您的密码:')
        if name == username and pwd == password:
            print('登录成功')
            while 1:
                cmd = input("输入命令>:")
                if cmd.lower() == "q":
                    break
                else:
                    print(f'命令{cmd}正在运行')
            break
        else:
            print("账号或密码错误")
    else:
        print('输错账号密码次数过多,退出')
    
    
    
    # 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
    name = " aleX"
    # 1)    移除 name 变量对应的值两边的空格,并输出处理结果
    print(name.strip())
    # 2)    判断 name 变量对应的值是否以 "al" 开头,并输出结果

    print(name.startswith("al"))
    # 3)    判断 name 变量对应的值是否以 "X" 结尾,并输出结果

    print(name.endswith("x"))
    # 4)    将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
    print(name.replace("l","p"))
    # 5)    将 name 变量对应的值根据 “l” 分割,并输出结果。
    print(name.split("l"))
    # 6)    将 name 变量对应的值变大写,并输出结果

    print(name.upper())
    # 7)    将 name 变量对应的值变小写,并输出结果

    print(name.lower())
    # 8)    请输出 name 变量对应的值的第 2 个字符?
    print(name[1])
    # 9)    请输出 name 变量对应的值的前 3 个字符?
    print(name[:3])
    # 10)    请输出 name 变量对应的值的后 2 个字符?

    print(name[-2:])
    # 11)    请输出 name 变量对应的值中 “e” 所在索引位置?

    print(name.find("e"))
    # 12)    获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。
    print(name[:-1])
    

    3月9号

    # 作业(必做题):
    #1. 使用while循环输出1 2 3 4 5 6     8 9 10
    a = 1
    while a <= 10:
        if a == 7:
            print(" ")
            a += 1
            continue
        print(a)
        a += 1
        
    #2. 求1-100的所有数的和
    a = 1
    sum = 0
    while a <= 100:
        sum += a
        a += 1
    print(sum)
    
    #3. 输出 1-100 内的所有奇数
    a = 1
    while a <= 100:
        if a % 2 == 1:
            print(a)
            a += 1
        a += 1
        
    #4. 输出 1-100 内的所有偶数
    a = 1
    while a <= 100:
        if a % 2 == 0:
            print(a)
            a += 1
        a += 1
        
    #5. 求1-2+3-4+5 ... 99的所有数的和
    a = 1
    sum = 0
    while a < 100:
        if a % 2 == 1:
            sum += a
            a += 1
        else:
            sum -= a
            a += 1
    print(sum)
    
    #6. 用户登陆(三次机会重试)
    user = {"jack":"123","lili":"radfd"}
    count = 1
    while count <= 3:
        name = input("请输入用户名:")
        password = input("请输入密码:")
        if name in user :
            if not user.get(name) == password:
                count += 1
                print("密码错误")
            else:
                print("登录成功")
                break
        else:
            print("用户名不存在")
    print("------end-----")
    
    #7:猜年龄游戏
        # 要求:
        # 允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出
    age = 23
    count = 0
    while count < 3:
        age_ges = input("请输入年龄:")
        if int(age_ges) == age:
            print("恭喜你猜对了")
            break
        else:
            count += 1
            print("你猜错了")
    else:
        print("------end-----")
    
    #8:猜年龄游戏升级版(选做题)
    # 要求:
    #     允许用户最多尝试3次
    #     每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序
    #     如何猜对了,就直接退出
    age = 23
    count = 0
    while True:
        age_ges = input("请输入年龄:")
        if int(age_ges) == age:
            print("恭喜你猜对了")
            break
        else:
            count += 1
            print("你猜错了")
            if count == 3:
                flag = input("继续游戏Y,退出游戏N:")
                if flag.upper() == "Y":
                    count = 0
                else:
                    break
    print("------end-----")
    
    
    
  • 相关阅读:
    14_java之变量|参数|返回值|修饰符
    NYOJ 202 红黑树 (二叉树)
    NYOJ 138 找球号(二) (哈希)
    NYOJ 136 等式 (哈希)
    NYOJ 133 子序列 (离散化)
    NYOJ 129 树的判定 (并查集)
    NYOJ 117 求逆序数 (树状数组)
    NYOJ 93 汉诺塔 (数学)
    HDU 2050 折线分割平面 (数学)
    天梯赛L2-008 最长对称子串 (字符串处理)
  • 原文地址:https://www.cnblogs.com/chenwenyin/p/12449015.html
Copyright © 2011-2022 走看看