字典有关练习:购物车

简单购物车
#
# 实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  
# msg_dic = {
# 'apple': 10,
# 'tesla': 100000,
# 'mac': 3000,
# 'lenovo': 30000,
# 'chicken': 10,
# }
方法一:
msg_dic = {
    'apple': 10,
    'tesla': 100000,
    'mac': 3000,
    'lenovo': 30000,
    'chicken': 10,
}
flag = True
good_list = {}
while flag:
    print('-----主菜单---按q退出---')
    for k in msg_dic:
        print(k,'====>',msg_dic[k])
    good = input('请输入您要购买的商品:').strip()
    if good == 'q': flag = False
    if good and good in msg_dic:#输入有效商品名
        while flag:
            num = input('请输入购买的数量:').strip()
            if num == 'q':
                flag = False
            elif num and num.isdigit():#输入有效数量
                num = int(num)
                good_list[good] = num if good not in good_list else good_list[good] + num# 修改购物车中的商品数量
                print('成功购买%s个%s'%(num,good),'==>',good_list)
                break
            else:
                print('请输入整数')
    else:
        print('请输入有效商品')

方法二:

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
goods_l=[]
while True:
    for k in msg_dic:
        print('NAME:33[41m<{name}>33[0m  PRICE:33[46m<{price}>33[0m'.format(name=k,price=msg_dic[k]))
    name=input('please input your goods name: ').strip()
    if len(name) == 0 or name not in msg_dic:continue
    while True:
        count=input('please input your count: ').strip()
        if count.isdigit():break

    goods_l.append((name,msg_dic[name],int(count)))
    print(goods_l)
View Code
原文地址:https://www.cnblogs.com/kxllong/p/7217929.html