python使用pickle和json模擬一個購物車

這是本人在學(xué)習(xí)python過程中寫的小程序,記錄下來。

代碼如下:

hon
# _*_ coding:utf-8 _*_
__author__ = 'junxi'

import pickle
import json
import sys



# 初始序列化pkl文件,用來存儲余額和已購商品
money = {
    'money': 0,     # 初始金錢
}
goods = []      # 初始已買物品欄,商品為空。
pkfile_write = open('data.pkl', 'wb')   # 以寫的方式打開文件
pickle.dump(money, pkfile_write)
pickle.dump(goods, pkfile_write)
pkfile_write.close()    # 關(guān)閉文件
# print '初始化pkl文件成功'


# 反序列化pkl文件,轉(zhuǎn)換為Python的可操作數(shù)據(jù)對象
pkfile_read = open('data.pkl', 'rb')    # 以只讀方式打開文件
money = pickle.load(pkfile_read)
goods = pickle.load(pkfile_read)
pkfile_read.close()         # 關(guān)閉文件
# print '賬戶金額:', money['money']
login_user = ''     # 登錄用戶
shopping_budget = ''    # 購物預(yù)算資金


def login():
    # 登錄驗(yàn)證
    global login_user
    username = ['admin', 'junxi', 'tangyan']        # 賬戶表
    password = {'junxi': 'junxi2017', 'admin': 'admin2017', 'tangyan': 'tangyan2017'}   # 密碼字典
    err_num = 0
    while True:
        # 內(nèi)容盒子
        welcomes = '          尊敬的客戶,歡迎您來到仙靈購物'
        screen_width = 80
        text_width = len(welcomes)
        box_width = text_width + 6
        left_margin = (screen_width - box_width) // 2
        print
        print '' * left_margin + '+' + '_' * (box_width - 2) + '+'
        print '' * left_margin + '| ' + ' ' * text_width + '   |'
        print '' * left_margin + '| ' + welcomes + '                  |'
        print '' * left_margin + '| ' + ' ' * text_width + '   |'
        print '' * left_margin + '+' + '_' * (box_width - 2) + '+'
        print

        if err_num == 3:
            print '輸入賬戶或密碼連續(xù)錯誤三次,請稍后再試'
            break
        user_input = raw_input('請輸入用戶名:')
        pass_input = raw_input('請輸入密碼:')
        login_user = user_input
        if user_input in username and pass_input == password[user_input]:
            print '登錄成功,welcome'
            # break
            shop_budget()   # 進(jìn)入購物預(yù)算判定
        elif user_input not in username:
            print '賬戶不存在,請重新輸入'
            err_num += 1
        elif pass_input != password[user_input]:
            print '密碼不正確,請重新輸入'
            err_num += 1
        else:
            print '用戶名或密碼不正確,請重新輸入'
            err_num += 1


# 購物預(yù)算
def shop_budget():
    global shopping_budget
    shopping_budget = int(raw_input('請問您帶了多少錢? >'))
    # 把購物預(yù)算金額寫入pkl文件
    pkfile_write = open('data.pkl', 'wb')  # 以可寫方式打開文件
    money['money'] = shopping_budget
    pickle.dump(money, pkfile_write)
    print '購物預(yù)算金額:', shopping_budget
    pkfile_write.close()

    if shopping_budget < 10:
        print 'Sorry,您的購物預(yù)算太低,無法在此消費(fèi),請攜帶充足金錢再來!'
        sys.exit(0)
    else:
        store_info()    # 資金符合要求,進(jìn)入商品詳情頁


# 商品詳情頁
def store_info():
    while True:
        try:
            if money['money'] < 10:     # 判斷余額
                print '您的余額已不足,請離開,歡迎下次光臨。'
                break
            elif money['money'] >= 10 and money['money'] < 20:
                print '您的余額已不足20元,您還可以嚼個口香糖'
            else:
                pass
            choice_list = [('咖啡', 50), ('iphone7 plus', 8888), ('未來人類筆記本', 28888), ('綠箭口香糖', 10), ('大天朝浮夸香煙', 688), ('海南爽口椰子果', 588),
                 ('瘋狂烤翅', 20), ('巨無霸漢堡', 25), ('女神陪游泳卡片', 6666)]
            # print json.dumps(choice_list, encoding='UTF-8', ensure_ascii=False)  # 解決中文亂碼問題
            prompt = '''%s,您好,歡迎來到仙靈大商城,您可選擇的商品信息如下,
            (0)咖啡                      50元
            (1)iphone7 plus             8888元
            (2)未來人類筆記本           28888元
            (3)綠箭口香糖               10元
            (4)大天朝浮夸香煙           688元
            (5)海南爽口椰子果           588元
            (6)瘋狂烤翅                 20元
            (7)巨無霸漢堡               25元
            (8)女神陪游泳卡片           6666元
            (9)退出
            請選擇您想要購買的商品(輸入數(shù)字即可)
            ---------------------------------------------

            您的可用余額為:%s元

            ---------------------------------------------
            input>''' % (login_user, money['money'])    # 登錄賬戶, 余額

            choice_input = int(raw_input(prompt))   # 用戶輸入的商品ID
            if choice_input == 9:
                print '已退出商城,歡迎下次光臨'
                break
            print '    您選擇購買%s' % (choice_list[choice_input][0])    # 購買的商品
            shopping_num = int(raw_input('    請輸入購買%s的數(shù)量:' % (choice_list[choice_input][0])))   # 商品數(shù)量
            print '    加入購物車成功,總價(jià):%s' % (choice_list[choice_input][1] * shopping_num)
            if (choice_list[choice_input][1] * shopping_num) <= money['money']:
                print '    你的資金充足,請付款'
                payment = int(raw_input('    請輸入1付款,0取消 >'))
                if payment == 1:
                    # 付款扣錢
                    pkfile_write = open('data.pkl', 'wb')  # 以可寫方式打開文件
                    buy_goods = (choice_list[choice_input][0], shopping_num)
                    goods.append(buy_goods)
                    cost_money = (choice_list[choice_input][1] * shopping_num)  # 花費(fèi)金額
                    current_money = money['money'] - cost_money  # 賬戶余額 - 花費(fèi)余額 = 當(dāng)前余額
                    money['money'] = current_money
                    pickle.dump(money, pkfile_write)    # 更新金錢余額
                    pickle.dump(goods, pkfile_write)  # 更新已買物品欄
                    pkfile_write.close()
                    print '    付款成功,商品已購買'
                    print '    當(dāng)前余額:', current_money
                else:
                    print '    訂單已取消,請重新選擇商品。'
            else:
                print '商品購買失敗,您的余額不足'

            if len(goods) > 0:
                print '恭喜您,買了這么多好東西:', json.dumps(goods, encoding='UTF-8', ensure_ascii=False)
        except:
            print '\033[1;31;0m輸入錯誤,請重新輸入\033[0m'


def main():
    login()


if __name__ == '__main__':
    main()

運(yùn)行:

+___________________________________________________________+
|                                                           |
|           尊敬的客戶,歡迎您來到仙靈購物                  |
|                                                           |
+___________________________________________________________+

請輸入用戶名:admin
請輸入密碼:admin2017
登錄成功,welcome
請問您帶了多少錢? >100000
購物預(yù)算金額: 100000
admin,您好,歡迎來到仙靈大商城,您可選擇的商品信息如下,
            (0)咖啡                      50元
            (1)iphone7 plus             8888元
            (2)未來人類筆記本           28888元
            (3)綠箭口香糖               10元
            (4)大天朝浮夸香煙           688元
            (5)海南爽口椰子果           588元
            (6)瘋狂烤翅                 20元
            (7)巨無霸漢堡               25元
            (8)女神陪游泳卡片           6666元
            (9)退出
            請選擇您想要購買的商品(輸入數(shù)字即可)
            ---------------------------------------------

            您的可用余額為:100000元

            ---------------------------------------------
            input>2
    您選擇購買未來人類筆記本
    請輸入購買未來人類筆記本的數(shù)量:2
    加入購物車成功,總價(jià):57776
    你的資金充足,請付款
    請輸入1付款,0取消 >1
    付款成功,商品已購買
    當(dāng)前余額: 42224
恭喜您,買了這么多好東西: [["未來人類筆記本", 2]]
admin,您好,歡迎來到仙靈大商城,您可選擇的商品信息如下,
            (0)咖啡                      50元
            (1)iphone7 plus             8888元
            (2)未來人類筆記本           28888元
            (3)綠箭口香糖               10元
            (4)大天朝浮夸香煙           688元
            (5)海南爽口椰子果           588元
            (6)瘋狂烤翅                 20元
            (7)巨無霸漢堡               25元
            (8)女神陪游泳卡片           6666元
            (9)退出
            請選擇您想要購買的商品(輸入數(shù)字即可)
            ---------------------------------------------

            您的可用余額為:42224元

            ---------------------------------------------
            input>8
    您選擇購買女神陪游泳卡片
    請輸入購買女神陪游泳卡片的數(shù)量:5
    加入購物車成功,總價(jià):33330
    你的資金充足,請付款
    請輸入1付款,0取消 >1
    付款成功,商品已購買
    當(dāng)前余額: 8894
恭喜您,買了這么多好東西: [["未來人類筆記本", 2], ["女神陪游泳卡片", 5]]
admin,您好,歡迎來到仙靈大商城,您可選擇的商品信息如下,
            (0)咖啡                      50元
            (1)iphone7 plus             8888元
            (2)未來人類筆記本           28888元
            (3)綠箭口香糖               10元
            (4)大天朝浮夸香煙           688元
            (5)海南爽口椰子果           588元
            (6)瘋狂烤翅                 20元
            (7)巨無霸漢堡               25元
            (8)女神陪游泳卡片           6666元
            (9)退出
            請選擇您想要購買的商品(輸入數(shù)字即可)
            ---------------------------------------------

            您的可用余額為:8894元

            ---------------------------------------------
            input>1
    您選擇購買iphone7 plus
    請輸入購買iphone7 plus的數(shù)量:1
    加入購物車成功,總價(jià):8888
    你的資金充足,請付款
    請輸入1付款,0取消 >1
    付款成功,商品已購買
    當(dāng)前余額: 6
恭喜您,買了這么多好東西: [["未來人類筆記本", 2], ["女神陪游泳卡片", 5], ["iphone7 plus", 1]]
您的余額已不足,請離開,歡迎下次光臨。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,556評論 25 708
  • 延續(xù)昨日觀點(diǎn),主趨勢上黃金相對最近的支撐級別,仍有下行空間。最近支撐點(diǎn)為1238.16,下方次級支撐區(qū)間為1223...
    雅典娜_2358閱讀 459評論 0 1
  • 老話說:“人過四十不學(xué)藝”。 我已四十有五,按老話來說,我是不是該休息一下了。收收心,養(yǎng)養(yǎng)花,種種草。但是不行,總...
    郭倍貝貝閱讀 1,736評論 0 0
  • Binary Tree Level Order Traversal 今天是一道有關(guān)二叉樹的題目,來自LeetCod...
    ab409閱讀 533評論 0 0