作業(yè):購物車
一新博、作業(yè)要求
- 優(yōu)化購物程序巧号,購買時(shí)允許用戶選擇購買多少件
- 允許多用戶登錄,下一次登錄后蹄咖,繼續(xù)按上次的余額繼續(xù)購買(可以充值)
- 允許用戶查看之前的購買記錄(記錄要顯示商品購買時(shí)間)
- 商品列表分級(jí)展示根盒。
- 顯示已購買商品時(shí)钳幅,如果有重復(fù)的商品,不打印多行炎滞,而是在一行展示贡这。
二、簡單思路
- 將Day01的兩個(gè)作業(yè)融合進(jìn)來厂榛,完成登錄驗(yàn)證和商品列表。
- 記錄用戶的剩余金額以及累計(jì)充值金額丽惭,并保存至對(duì)應(yīng)的金額文件击奶。
- 用戶的購買行為信息存為列表,并保存至對(duì)應(yīng)的購買記錄文件责掏。
- 多次購買的商品信息存為字典柜砾,并保存至對(duì)應(yīng)的已購清單文件。
三换衬、流程圖
四痰驱、新知識(shí)點(diǎn)自學(xué)
- Python 日期和時(shí)間
- 序列化
- 讀寫JSON數(shù)據(jù)
五证芭、代碼
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# Author: Will
import os
import getpass
import time
import json
# 黑名單
if not os.path.exists('blacklist.txt'):
with open('blacklist.txt', 'a+') as f:
f.read()
# 賬戶登錄
print("""
********************************************
** **
** **
** 歡迎來到賬戶登錄界面 **
** **
** **
** **
********************************************
""")
true_username = 'will'
true_password = '1234'
for i in range(3):
with open('blacklist.txt', 'r') as f:
blacklist = f.read().split()
# print(blacklist)
username = input("請(qǐng)輸入您的用戶名:")
if username in blacklist:
print("您的賬戶: %s 已經(jīng)被鎖定。請(qǐng)聯(lián)系管理員解鎖担映,或者更換登錄賬戶废士。" % username)
continue
else:
password = getpass.getpass("請(qǐng)輸入您的密碼:")
if true_username == username and true_password == password:
print("""
********************************************
** **
** 這里是“沒什么東西可買商城” **
** **
** 歡迎您的光臨,%s **
** **
** **
********************************************
""" % username)
break
elif i == 2:
with open('blacklist.txt', 'a+') as f:
f.write('%s\n' % username)
exit("您已嘗試登錄3次蝇完,您的賬戶 %s 已被鎖定官硝。" % username)
else:
print("用戶名或密碼錯(cuò)誤,請(qǐng)重試短蜕。")
# 資金余額和已購清單文件讀取
if os.path.exists('purchased_list.txt'):
with open('purchased_list.txt', 'r') as f:
purchased_list = json.load(f)
with open('salary.txt', 'r') as f:
salary = json.load(f)
# salary = purchased_list.get('Salary')
# print(purchased_list)
else:
purchased_list = {}
salary_flag = False
while not salary_flag:
salary = input("請(qǐng)輸入您要充值的金額('q':退出):")
if salary.isdigit():
salary = int(salary)
salary_flag = True
elif salary == 'q':
exit()
else:
print("輸入格式不正確氢架,請(qǐng)輸入數(shù)字。")
print("您現(xiàn)在的資金余額為:%d元\n" % salary)
# 商品字典
goods = {
'圖書類': [
('魔鬼經(jīng)濟(jì)學(xué)', 135), ('權(quán)力的游戲', 285), ('莎士比亞悲劇喜劇全集', 109)
],
'3C類': [
('iPhone7 Plus', 5000), ('Macbook Pro', 20000), ('Dell XPS15', 12000)
],
'家電類': [
('電視機(jī)', 5000), ('電冰箱', 7000), ('空調(diào)', 4000)
],
'服裝類': [
('羽絨服', 1200), ('牛仔褲', 500), ('毛呢大衣', 1800)
]
}
# 根據(jù)當(dāng)前目錄是否有purchased_info文件來判斷是讀取文件信息還是賦空值
if os.path.exists('purchased_info.txt'):
with open('purchased_info.txt', 'r') as f:
purchased_info = json.load(f)
else:
purchased_info = []
# 購物車
shopping_flag = False
while not shopping_flag:
print("“沒什么東西可買商城”商品目錄:")
for menu1 in enumerate(goods):
print(menu1[0], menu1[1])
catagory = input("\n請(qǐng)選擇您想瀏覽的商品目錄編號(hào)('r':查看購買記錄朋魔,'c':查看已購清單岖研,'q':退出):")
if catagory.isdigit():
catagory = int(catagory)
if catagory < len(goods):
key = list(goods)[catagory]
else:
print("請(qǐng)輸入正確的商品編號(hào)。")
while catagory < len(goods):
print("\n“沒什么東西可買商城” %s商品列表:" % key)
for menu2 in enumerate(goods[key]):
print(menu2[0], menu2[1][0], menu2[1][1])
user_choice = input("\n請(qǐng)輸入您想購買的商品編號(hào)('r':查看購買記錄警检,'c':查看已購清單孙援,'b':返回,'q':退出):")
if user_choice.isdigit(): # 如果用戶選擇輸入的是數(shù)字
user_choice = int(user_choice)
if user_choice < len(goods[key]):
purchased_amount = input("請(qǐng)輸入你要購買的數(shù)量:")
if purchased_amount.isdigit():
purchased_amount = int(purchased_amount)
purchased_item = goods[key][user_choice] # 將選擇的商品賦值給purchased_item
if purchased_item[1] * purchased_amount <= salary: # 商品總價(jià)小于等于資金余額
salary -= purchased_item[1] * purchased_amount
purchased_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) # 將購買時(shí)間記錄下來賦值給purchased_time
purchased_record = [purchased_item[0], purchased_item[1], purchased_amount, purchased_time] # 將商品名解滓,商品價(jià)格赃磨,購買數(shù)量,購買時(shí)間以列表計(jì)入purchased_record
purchased_info.append(purchased_record) # 將本條購買記錄添加進(jìn)purchased_info
# print(purchased_info)
with open('purchased_info.txt', 'w') as f: # 將當(dāng)前的購買記錄寫入文件purchased_info.txt
json.dump(purchased_info, f)
with open('salary.txt', 'w') as f: # 將當(dāng)前資金余額寫入資金文件salary.txt
json.dump(salary, f)
# 根據(jù)已購清單中是否有商品信息判斷
if purchased_item[0] in purchased_list: # 如果已購清單中已有商品信息洼裤,最新已購數(shù)量 = 此次購買數(shù) + 已購買數(shù)
purchased_amount_new = purchased_amount + purchased_list.get(purchased_item[0])
else:
purchased_amount_new = purchased_amount # 如果已購清單中沒有商品信息邻辉,最新已購數(shù)量 = 此次購買數(shù)
purchased_list[purchased_item[0]] = purchased_amount_new # 修改已購清單字典purchased_list中對(duì)應(yīng)商品的最新已購數(shù)量
with open('purchased_list.txt', 'w') as f: # 將已購清單字典purchased_list寫入已購清單文件purchased_list
json.dump(purchased_list, f)
# print(purchased_list)
print("\n您購買了 “%s” ,數(shù)量:%d腮鞍,共計(jì) %d元" % (purchased_item[0], purchased_amount,
purchased_item[1] * purchased_amount))
print("您現(xiàn)在的資金余額為:%d元\n" % salary)
else:
recharge = input("\n您的資金余額不足值骇,請(qǐng)輸入您要充值的金額(輸入'n'退出):")
if recharge.isdigit():
recharge = int(recharge)
salary += recharge # 充值
print("您現(xiàn)在的資金余額為:%d元\n" % salary)
elif recharge == 'n':
exit("感謝您的光臨,祝你本次購物愉快移国,再見吱瘩。")
else:
print("請(qǐng)正確輸入您想要充值的金額。\n")
else:
print("正確購買的數(shù)量應(yīng)該為數(shù)字迹缀。\n")
else:
print("請(qǐng)您輸入正確的商品編號(hào)使碾。\n")
elif user_choice == 'b':
break
elif user_choice == 'r':
for items in purchased_info: # 循環(huán)購買記錄列表
print("您在 %s 購買了 “%s” ,單價(jià):%d元祝懂,數(shù)量:%d 票摇,共計(jì):%d元" % (
items[3], items[0], items[1], items[2], items[1] * items[2]))
print("您現(xiàn)在的資金余額為:%d元\n" % salary)
elif user_choice == 'c':
for items in purchased_list: # 循環(huán)已購清單字典
print("您目前已購買了 “%s” ,數(shù)量:%d" % (items, purchased_list[items]))
print("您現(xiàn)在的資金余額為:%d元\n" % salary)
elif user_choice == 'q':
for items in purchased_list: # 循環(huán)已購清單字典
print("您目前已購買了 “%s” 砚蓬,數(shù)量:%d" % (items, purchased_list[items]))
exit("您現(xiàn)在的資金余額為:%d元\n" % salary)
else:
print("您輸入了非法字符矢门,請(qǐng)輸入數(shù)字。\n")
elif catagory == 'r':
for items in purchased_info: # 循環(huán)購買記錄列表
print("您在 %s 購買了 “%s” ,單價(jià):%d元祟剔,數(shù)量:%d 隔躲,共計(jì):%d元" % (
items[3], items[0], items[1], items[2], items[1] * items[2]))
print("您現(xiàn)在的資金余額為:%d元\n" % salary)
elif catagory == 'c':
for items in purchased_list: # 循環(huán)已購清單字典
print("您目前已購買了 “%s” ,數(shù)量:%d" % (items, purchased_list[items]))
print("您現(xiàn)在的資金余額為:%d元\n" % salary)
elif catagory == 'q':
for items in purchased_list: # 循環(huán)已購清單字典
print("您目前已購買了 “%s” 物延,數(shù)量:%d" % (items, purchased_list[items]))
exit("您現(xiàn)在的資金余額為:%d元\n" % salary)
else:
print("您輸入了非法字符宣旱,請(qǐng)您輸入數(shù)字。\n")