购物车代码

看到老师和同学们在写购物车代码,自己也写了一个,花费时间3个小时,初步实现了购物车的基本功能,先放在这,以后慢慢优化。这也是自己第一次,写这么多行的代码

dic={'香蕉':5,'苹果':3,'橘子':4}
dict1={'香蕉':0,'苹果':0,'橘子':0}
str2=''
str3=''
str4=''
str5=''
str6=''
str7=''
str8=''
str9=''
Money=300
print(dic)
pocket=300
while 1:
    str1 = input('欢迎光临大锤水果店,请问您需要购买什么:').strip()
    if int(str1)>=len(list(dic)):
        print('请输入正确的数字')
    else:
        if int(str1)==0:
            str2='香蕉'
            str2_1=int(input('购买香蕉的数量:'))+dict1['香蕉']
            dict1['香蕉'] = int(str2_1)
        if int(str1)==1:
            str3='苹果'
            str3_1 =int(input('购买苹果的数量:'))+dict1['苹果']
            dict1['苹果']=int(str3_1)
        if int(str1)==2:
            str4='橘子'
            str4_1=int(input('购买橘子的数量:'))+dict1['橘子']
            dict1['橘子']=int(str4_1)
        str5=input('是否还需要购买其他商品(y/n):')
        if str5.upper()=='Y':
            continue
        else:
            break
        break
print(dict1)
if dict1['香蕉']>0:
    str6='香蕉,数量{}千克'.format(dict1['香蕉'])
if dict1['苹果']>0:
    str7='苹果,数量{}千克'.format(dict1['苹果'])
if dict1['橘子']>0:
    str8='橘子,数量{}千克'.format(dict1['橘子'])
str9='您选择的商品有:'+str6+str7+str8
print(str9)
Tmoney=int(dic['香蕉'])*dict1['香蕉']+int(dic['苹果'])*dict1['苹果']+int(dic['橘子'])*dict1['橘子']
print('本次消费金额为:{}元'.format(Tmoney))
pocket=pocket-Tmoney
if pocket<0:
    print('您的余额不足,请及时充值')
else:
    print('欢迎下次光临,请慢走,您的余额为{}元'.format(pocket))

 这是老师的代码

li=[
    {'name':'苹果','price':10},
    {'name':'香蕉','price':20},
    {'name':'西瓜','price':30},
]#把货物放在货架上
shopping_car={}
print('欢迎来到大铁锤水果店')
money=input('让我看看你的钱')
while 1:
    if money.isdigit() and int(money)>0:
        for i,k in enumerate(li):
            print('序号{},商品{},价格{}'.format(i,k['name'],k['price']))
        choose=input('请输入您要购买商品的序号')
        if choose.isdigit() and int(choose)<len(li):
            num=input('您要购买的商品数量')
            if num.isdigit():
                if int(money)>li[int(choose)]['price']*int(num):
                    money=int(money)-li[int(choose)]['price']*int(num)
                if li[int(choose)]['name'] in shopping_car:
                    shopping_car[li[int(choose)]['name']]=shopping_car[li[int(choose)]['name']]+int(num)
                else:
                    shopping_car[li[int(choose)]['name']]=int(num)
                print('购物车中的商品有{},您的余额为{}'.format(shopping_car,money))
            else:
                print('穷鬼,回去给你老婆要钱!')
                break
        else:
        print('都说了是序号,你傻呀!')

 

 

posted @ 2019-01-05 19:04  舒畅123  阅读(806)  评论(0编辑  收藏  举报