1. 程式人生 > 實用技巧 >購物車終極版

購物車終極版

購物車終極版

#需求:1.可自由管理入購物車
    # 2.當瀏覽商品時,顯示當前頁碼,以及共幾頁
    # 3.設計一個返回的操作,即返回上一層函式,或直接退出的選項
    # 4.先登入系統或者註冊才能繼續後續操作
    # 5.商品瀏覽時,可選擇全部瀏覽或者分頁瀏覽
    # 6.做一個搜尋框,可以搜尋需要的商品
    # 7.使用者名稱輸錯三次便強制退出,1分鐘後才可以繼續輸入,並顯示剩餘可輸入的次數
    # 8.對管理員和使用者做區分
def blacklist():
    '''
    拉進黑名單的操作
    :return:
    pass
    '''
    name = input("請輸入你要拉黑的姓名:")
    with open("dongjie.txt",'a',encoding = "utf-8")as f:
        f.write(name)
    f.close()


def serch():
    '''
    商品搜尋
    :return:
    '''
    while True:
        select = input("請輸入要搜尋的內容(n返回):")
        if select.upper() == "N":
            return run()
        with open("zidian",'r',encoding="utf-8")as f:
            val = f.readlines()
            lis = [item.strip("\n") for item in val]
            flag = False
            for i in lis:
                v = eval(i)
                if v.get("title") == select:
                    flag = True
                    print(v)
            if not flag:
                print("所搜尋的內容不存在,請重新輸入吧")
                continue


def log():
    '''
    使用者登入
    :return:
    部分返回主函式
    '''
    count = 1
    import time
    while True:
        print("***************使用者登入***************")
        user_name = input("請輸入使用者名稱(n返回):")
        if user_name.upper() == "N":
            return run()
        user_pwd = input("請輸入登入密碼:")
        count = count + 1
        with open("dongjie.txt", 'r', encoding='utf-8') as f:
            user_info = f.readlines()
            new_user_info = [item.strip() for item in user_info if item.strip()]  # strip與if的搭配也要值得注意
            if user_name in new_user_info:
                print("你的賬戶已被凍結,強制退出")
                return
        f.close()
        user_exit = False
        flag = False
        with open("zhuce", "r", encoding="utf-8") as f1:
            for line in f1:
                user_name1, user_pwd1, time1 = line.split("|")
                #與註冊的格式有關,應先註冊
                if user_name == user_name1:
                    user_exit = True
                if user_name == user_name1 and user_pwd == user_pwd1:
                    flag = True
                    print("你已經登入系統")
                    choice = input("請選擇接下來的服務型別(n返回)\n(1:商品瀏覽 2:我的購物車 3:搜尋商品):")
                    if choice.upper() == "N":
                        return log()
                    num = int(choice)
                    dic = {1: browse, 2: shopping_car, 3:serch}
                    func = dic.get(num) #呼叫次一級函式
                    func()
            if count > 3:
                print("登入次數已用完,賬戶凍結1分鐘,1分鐘後重新輸入")
                time.sleep(60) #賬戶凍結600秒
                continue
            if not user_exit:
                print("使用者名稱不存在,請重新輸入,剩餘登入次數%s"%(4-count))
                continue
            if not flag:
                print("使用者名稱或密碼錯誤,剩餘登入次數%s"%(4-count))


def register():
    '''
    使用者註冊
    :return:
    部分返回主函式
    '''
    from datetime import datetime
    print("---------使用者註冊-----------")
    while True:
        user_name = input("請輸入使用者名稱(N返回):")
        if user_name.upper() == "N":
            return run()
        user_pwd = input("請輸入登入密碼:")
        creat_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with open("zhuce", 'a', encoding='utf-8') as f:
            line = "%s|%s|%s\n" % (user_name, user_pwd, creat_time)
            f.write(line)
        f.close()


def browse():
    '''
    商品瀏覽
    :return:
    部分返回主函式
    '''
    def select1():
        '''
        全域性瀏覽
        :return:
        pass
        '''
        with open("zidian", 'r', encoding='utf-8') as f:
            result = f.readlines()
            val = [item.strip("\n") for item in result]
            for i in val:
                print(i)
    def select2():
        '''
        分頁瀏覽
        :return:
        pass
        '''
        with open("zidian", 'r', encoding='utf-8') as f:
            lis = []
            count = 0
            count_num = len(f.readlines())  # 生成一個計數器
            number = count_num // 4 + 1
            f.seek(0)
            while True:
                choice = input("請輸入要瀏覽的頁碼(n返回):")  # 大於0切合法
                if choice.upper() == "N":
                    return browse()
                num = int(choice)
                if num > number:
                    print("最大頁碼為%s,請重新輸入" % number)
                    continue
                star_info = (num - 1) * 4
                end_info = num * 4
                for line in f:
                    count += 1
                    if count > star_info:
                        lis.append(line)
                    if count >= end_info:
                        break
                print("當前頁碼為%s,共%s頁" % (num, number), )
                for i in lis:
                    val = i.strip("\n")
                    print(val)
        f.close()

    select = input("請選擇你的瀏覽方式(1.全域性瀏覽 2.分頁瀏覽):")
    dic = {"1":select1,"2":select2}#觸發不同的函式
    val = dic.get(select)
    val()


def shopping_car():
    '''
    我的購物車
    :return:
    pass
    '''
    # 購物車
    SHOPPING_CAR = {}
    GOODS_LIST = []

    with open("zidian", 'r', encoding ="utf-8") as f:
        for item in f:
            GOODS_LIST.append(eval(item))
            ###需要加裝飾器
    for i in range(len(GOODS_LIST)):
        print(i + 1, GOODS_LIST[i]["title"])
    while True:
        choice = input("請選擇商品的序列號(n返回):")
        if choice.upper() == "N":
            return run()
        num = int(input("請選擇需要商品的數量:"))
        row_info = GOODS_LIST[int(choice) - 1]
        if row_info["id"] in SHOPPING_CAR:  # 標誌物
            SHOPPING_CAR[row_info["id"]]["count"] += num  # 需要定義SHOPPING_CAR的型別
        else:
            SHOPPING_CAR[row_info['id']] = {"title": row_info["title"], "price": row_info["price"],
                                            "count": num}  # 鍵值對的生成
        print(SHOPPING_CAR)

def see_white():
    with open("zhuce","r",encoding="utf-8")as f:
        result = f.read()
        print(result)
    f.close()
def see_black():
    with open("dongjie.txt","r",encoding="utf-8")as f:
        result = f.read()
        print(result)
    f.close()


def adm():
    '''
    管理員程式主介面
    :return:
    pass
    '''
    question = input("口令?(提示:who is u dad?):")
    if question == "楊子良":
        chioce = input("請選擇服務型別(n退出程式):1.檢視使用者資訊 2.檢視黑名單 3.增加黑名單:")
        if chioce.upper() == "N":
            return
        num = int(chioce)
        dic = {1: see_white, 2: see_black,3:blacklist }
        func = dic.get(num)
        func()


def run():
    '''
    使用者主介面
    :return:
    部分退出程式
    '''
    print("1:使用者登入,2:使用者註冊")
    chioce = input("請選擇服務的序號(n退出程式):")
    if chioce.upper() == "N":
        return
    num  = int(chioce)
    dic = {1:log,2:register,}
    func = dic.get(num)
    func()

def main():
    '''
    程式入口
    :return:
    '''
    print("*****************************歡迎來到我的購物商城*****************************")
    select = input("你是?1:客戶  2:管理員 :" ) #發出詢問,辨別身份
    dic = {"1":run,"2":adm}
    func = dic.get(select)
    func()
if __name__ == '__main__':
    main()

總結:

  • 優點:
    • 要求基本完成,而且內容相對完備
  • 缺點:
    • 不夠高階。基本還是函式的堆砌,沒有用到裝飾器之類的