自助购物系统(含文件读写)

自助购物系统

# 根据以下场景,模拟一个自助购物系统:

# 场景:市场上有一家新店开业,为了吸引顾客光临,现将部分商品出售,派克钢笔(单价200)、茶杯(单价50)、毛巾(单价20)、书(单价20)、拖鞋(单价10)等商品,每位顾客进店,可手持一个购物车进行选购商品。

功能细则如下:

1)可查看目前商品信息(商品名及单价);

2)查看当前购物车中商品信息:需要显示当前商品名称、商品单价、当前购物车商品数量等相关信息,以及购物车中商品总价;

3)添加商品到购物车:可根据商品名称,放入购物车中(默认添加一件);

4)减少移出购物车中的指定商品;:

定义了一个ShopSystem的类,在类中实现每一中操作

import os
import re
class ShopSystem:
    item=[]
    shopcard=[]
    def __init__(self):#初始化
        if os.path.getsize('  ShopSystem.txt') == 0:
            self.isempty()
        else:
            f=open('ShopSystem.txt','r')
            num=f.readlines()
            for i in num:
                name=re.findall('名称:(.*?)\t',i)
                price=re.findall('单价:(.*?)\t',i)
                count= re.findall('数量:(.*?)\n',i)
                self.item.append({'name': name[0], '单价': int(*price), 'count': int(*count)})
            f.close()
            try: 
                f1=open('shopcard.txt','r')
                cardnum=f1.readlines()
                for i in cardnum:
                    name=re.findall('名称:(.*?) ',i)
                    price=re.findall('单价:(.*?) ',i)
                    count= re.findall('数量:(.*?)\n',i)
                    self.shopcard.append({'name': name[0], '单价': int(*price), 'count': int(*count)})
                f.close()
            except :#抛出文件错误的异常,并初始化购物车
                self.isshopcardempty()
    def isempty(self):
        item = [{'name': '派克钢笔', '单价': 200, 'count': 20}, {'name': '茶杯', '单价': 50, 'count': 30},
                {'name': '毛巾', '单价': 20, 'count': 40},
                {'name': '书', '单价': 20, 'count': 20}, {'name': '拖鞋', '单价': 10, 'count': 40}]
        f = open('ShopSystem.txt', 'w')
        for i in item:
            f.write(f"商品名称:{i['name']}\t商品单价:{i['单价']}\t库存数量:{i['count']}\n")
        f.close()
    def isshopcardempty(self): #初始化购物车
        shopcard=[{'name':'书', '单价':20, 'count':1},{'name':'拖鞋', '单价':10, 'count':2}]
        f = open('shopcard.txt', 'w')
        for i in shopcard:
            f.write(f"商品名称:{i['name']}\t商品单价:{i['单价']}\t数量:{i['count']}\n")
        f.close()
    def buy(self,name,count): #购买商品 
        for i in range(0,len(self.item)):
            if name==self.item['name']:
                if count<=self.item[i]['count']:
                    self.item[i]['count']-=count
                else:
                    print('库存不足')
                    return -1
   def showitem(self,name): #显示商品信息
        for i in range(0,len(self.item)):
            if name==self.item[i]['name']:
                print(f"商品名称{self.item[i]['name']}、商品单价{self.item[i]['单价']}、当前商品数量:{self.item[i]['count']}")
                print('➀⚭加入购物车\n➁⚭进入主菜单')
                opt = int(input('请输入你要选择的操作:'))
                if opt == 1:
                    print(f'添加商品 {name} 到购物车')
                    self.addshop(name)
                elif opt == 2:
                    return
                else:
                    return
                break
            else:
                if i==len(self.item)-1:
                    print('\n△输入的商品不存在△\n')
def show_shopcart(self):
    n=0
    while n!=4:
        total = 0
        print('{:*^30}'.format('购物车'))
        for i in self.shopcard:
            print(f"商品名称{i['name']:^4}单价 {i['单价']:^3} 数量 {i['count']:^3} 总价 {i['单价']*i['count']:^3}")
            total+=i['单价']*i['count']
        print(f'❤商品总价为 {total}')
        print('*'*30)
        print('➀⚭删除商品\n➁、减少商品数量\n➂⚭查看商品详细信息\n➃⚭返回主菜单')
        try:
            n=int(input('请输入要操作的功能:'))
        except :
            print('\n△输入的功能不存在!返回主菜单△\n')
            break
        if n==1:
            name=input('请输入要删除商品的名称:')
            self.delshop(name)
        elif n==2:
            name = input('请输入要移除商品的名称:')
            for i in range(0,len(self.shopcard)):
                if name==self.shopcard[i]['name']:
                    if self.shopcard[i]['count']==1:
                        x=input('△该商品只有一个是否确认删除:(y/n)')
                        if x=='y':
                            self.shopcard.pop(i)
                    else:
                        self.shopcard[i]['count']-=1
            f = open('shopcard.txt', 'w')
            for i in self.item:
                f.write(f"商品名称:{i['name']}\t商品单价:{i['单价']}\t库存数量:{i['count']}\n")
            f.close()
        elif n==3:
            name=input('请输入要查看的商品名称:')
            self.showitem(name)
        else:
            return
def addshop(self,name):
    for j in range(0, len(self.item)):
        if name==self.item[j]['name']:
            for i in range(0, len(self.shopcard)):
                if name==self.shopcard[i]['name']:
                    self.shopcard[i]['count'] += 1
                    break
            if i == len(self.shopcard) - 1:
                self.shopcard.append({'name': self.item[j]['name'], '单价': self.item[j]['单价'], 'count': 1})
            break
    if j == len(self.item) - 1:
        print('\n△你输入的商品不存在△\n')

def delshop(self,name):
    for i in range(0, len(self.shopcard)):
        if name==self.shopcard[i]['name']:
            self.shopcard.pop(i)
            print('删除成功')
            break
def save(self):
    f = open('ShopSystem.txt', 'w')
    for i in self.item:
        f.write(f"商品名称:{i['name']}\t商品单价:{i['单价']}\t库存数量:{i['count']}\n")
    f.close()
    f1= open('shopcard.txt', 'w')
    for i in self.shopcard:
        f1.write(f"商品名称:{i['name']}\t商品单价:{i['单价']}\t数量:{i['count']}\n")
    f1.close()

主体内容

shop=ShopSystem()
n=0
while n!=3:
    print("{:◇^30}".format('欢迎来到※购物系统'))
    for i in shop.item:
        print(f"商品名称 {i['name']:<6}商品单价 {i['单价']:<4}")
    print('◇' * 30)
    print('➀⚭查看商品详细信息\n➁⚭查看购物车\n➂⚭退出系统')
    try:
        num=int(input('请选择要操作的功能:'))
    except ValueError:
        print('△'*30)
        print('{:△^30}'.format('输入的功能选项不合法请重新选择'))
        print('△' * 30)
        continue
    if num==1:
        name=input('请输入要查看的商品信息:')
        shop.showitem(name)
    elif num==2:
        shop.show_shopcart()
    elif num==3:
        shop.save()
        print('❧'*30)
        print('{:❦^30}'.format('谢谢惠顾'))
        print('❧' * 30)
        n=3
        break
    else:
        print('\n△无该功能△\n')
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值