购物车默写(程序一部分)

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
shopping_cart=[]
while True:
for k in msg_dic:
info='商品名:%s 价钱:%s' % (k, msg_dic[k])
print(info.center(50,' '))
name=input('请输入商品名>>: ').strip()
if name not in msg_dic: # name不为key值就走重输
# 输入的商品名不合法,打印提示信息并且直接进入下一次循环
print('输了些什么玩儿。。。重输')
continue
# else:
# #输入的商品品合法,结束循环
# break
while True:
count=input('请输入购买个数:').strip()
if count.isdigit():
#输入个数合法
count=int(count)
break
else:
print('商品的个数必须为整数')
# continue # 不加continue也会跳入下一次
#name,count
for item in shopping_cart:
# print(item)
if name == item['name']:
item['count']+=count
break
else: #for循环走完了没找到,没买过该商品;就是for else后面的。
price=msg_dic[name]
info={'name':name,'count':count,'price':price} #把拿到的数据name、count、price赋值到新的变量
shopping_cart.append(info) #再加入购物车
print(shopping_cart)

猜你喜欢

转载自www.cnblogs.com/wangcheng9418/p/9117955.html