将购物车程序分模块编程,购物车1写了登录 部分,下面改写购物部分:
#!/usr/bin/env python
product_list = [['Iphone7',5800],
['coffee',30],
['tea', 10],
['Python Book',99],
['Bike', 199],
['ViVo X9',2499]]
shopping_cart = {}
username = input("username:")
print("****************************")
password = input("password:")
print("****************************")
i = 1
while i <= 3: #登录判断
if username == "maomao" and password == "123":
print("welecom to shopping maket")
break
elif i == 3:
print("input more than three times, try again after 2 hours")
break
else:
print("you put an wrong name or password,please input again")
i += 1
username = input("username:")
password = input("password:")
print("*************** 系统操作说明 ****************")
print(" q : 退出系统")
print(" c : 账号充值")
print(" h : 购物记录")
print(" l : 商品列表")
print("************************************************")
salary = 0
while True: #充值判断
temp = input("you account is zear,please rechange money to buy:")
if temp.isdigit():
salary = int(temp)
break
print("you input a unknow number,please check it and input again!")
while True:
index = 0
for product in product_list: #打印商品列表,在商品之前添加序号,购物时只需要选择序号即可
print(index,product)
index += 1
choice = str(input(">>:")).strip()
if choice.isdigit(): #判断输入是否为数据
choice = int(choice)
if choice >= 0 and choice < len(product_list): #所选数字是否在商品序号范围内
product = product_list[choice]
if product[1] <= salary: #账户所剩金额是否够支付所选商品
if product[0] in shopping_cart: #同一种商品,多次购买,实现商品数量叠加
shopping_cart[product[0]][1] += 1
else:
shopping_cart[product[0]] = [product[1], 1]
salary -= product[1]
print("\033[42;1mAdded product:"+ product[0] +" into shoing cart ,you current balance "
+ str(salary)+"\033[0m")
else: #账户余额不足提醒
print("\033[42;1m [warning] you balance is no enough\033[0m, product:"+str(product[1])+" short for "
+ str(product[1]-salary))
else:
print("You choice product is no in product_list")
elif choice == "q": #退出
print("\033[34;1m---------------product list-----------------\033[0m")
print("\033[42;1m")
print("id product number pric Totalpric")
index = 1
total_mon = 0
f = open("product.txt","a+",encoding="utf8") #因为要记录多次购物记录,所以此处打开模式为追加写
import datetime
for i in shopping_cart.keys(): #打印购物列表,并打印商品数量,以及金额
total_mon += shopping_cart[i][1] * shopping_cart[i][0]
print("%d %10s %7d %7d %7d" %(index,i,shopping_cart[i][1], shopping_cart[i][0],
shopping_cart[i][1] *shopping_cart[i][0]))
if index == 1:
now_time = datetime.datetime.now().strftime('[%Y-%m-%d]')
f.write(now_time +"\n")
f.write(i+ "%7d"%+shopping_cart[i][0]+"\n") #保存购物列表
f.write(i + "\n")
index += 1
f.close()
print("you pay money is:", total_mon)
print("you level money is:", salary)
print("\033[0m")
print("\033[34;1m-------------end-------------\033[0m")
break
elif choice == "c": #充钱
salary += int(input("please input you recharge:"))
print("当前账户余额:",salary)
continue
elif choice == 'h':
f = open("product.txt", "r+", encoding="utf8")
for i in f:
print(i.strip())
continue
else:
print("You input wrong oper,please input again!")