首页 > 代码库 > 购物车小程序客户端

购物车小程序客户端

要求:

  1.用户输入金额后,就可以选择商品添加进购物车

  2.金额不足扣款时,提示用户余额不足

  3.当用户随时可以退出程序

  4.退出程序后自动保存金额和所购商品

# -*- coding:utf-8 -*-
import time
#分别打开商品列表的储存文件和余额列表的储存文件
with open (ware_list,r,encoding = utf-8)as ware:
    ware = eval(ware.read())
with open (balance,r+,encoding = utf-8) as balance:
    balance = eval(balance.read())

shopping_cart = []
warelist = []
#根据商品数量打印商品列表
def ware_list():
    print(---------商品列表-----------)
    count = 0
    for i in ware:
        count += 1
        print(count,.,i,    ,ware[i])
        if i in warelist:
            continue
        else:
            warelist.append(i)
def timmer():
    time.format =%Y-%m-%d %X
    time.current = time.strft(time.format)
    print(time.current)

#判断是否有余额文件如果有则将余额值赋予工资变量
if balance[balance] > 0:
    print((well come back! ur balance :{0} ur bought list :{1}).format(balance[balance],balance[shopping cart]))
    shopping_cart.extend(balance[shopping cart])
    salary = balance[balance]
else:
    salary = input(请输入您的工资:)
while True:
    salary = int(salary)
    ware_list()
    choice = input(你想购买什么商品?\n (输入Q退出))
        #如果输入为q则可以退出
    if choice.upper() == Q:
        request = input(请确认是否退出?Y/N)
        #
        if request.upper() ==  Y:
            break
        elif request.upper()== N:
            continue
        else:
            print(非法输入!!)
            continue
    elif len(choice)<= len(warelist):
        if salary - int(ware[warelist[int(choice)-1]]) > 0:
            shopping_cart.append(warelist[int(choice)-1])
            salary -= int(ware[warelist[int(choice)-1]])
            print((您已经购买:{0} 余额为:{1}).format(shopping_cart,salary))
            time.format =%Y-%m-%d %X
            time.current = time.strftime(time.format)
            print(time.current)

        else:
            print(您的余额不足购买该商品 请重新选择)

    else:
        print(请正确输入商品序号!)
        continue

#保存余额信息
print((您一共购买了{0}件商品,您的余额剩余:{1} 购买了:{2}).format(len(shopping_cart),salary,shopping_cart))
with open("balance",w,encoding=utf-8)as new:
    new.write("{‘balance‘:%d,‘shopping cart‘:%s}"%(salary,shopping_cart))

缺陷:无法针对回车等非法输入进行限制

思路:因为要求随时可以退出程序  所以减少循环层数是减少工作量提高代码运行效率的最好方式  所以我就只用了一个主循环

购物车小程序客户端