- msg_dic = {
- 'apple': 10,
- 'tesla': 100000,
- 'mac': 3000,
- 'lenovo': 30000,
- 'chicken': 10,
- }
- shopping_cart=[]
- tag = True
- while tag:
- for i in msg_dic:
- info = '商品名称是:%s 商品价格是:%s' %(i,msg_dic[i])
- print(info.center(50,' '))
- name =input('请输入购买的商品名:').strip()
- if name not in msg_dic:
- print('你输入的都是些什么几把玩意儿啊!')
- continue
- while True:
- count =input('请输入需要购买的个数:').strip()
- if count.isdigit():
- #print('输入合法')
- count = int(count)
- break
- else:
- print('请重新输入:')
- for item in shopping_cart:
- 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)
- flag = True
- while flag:
- choice = input('请选择继续 (Y/y) 购买, 或者退出(N/n):').strip()
- if choice == 'Y' or choice == 'y':
- break
- elif choice == 'N' or choice == 'n':
- print('退出成功, 欢迎下次使用!')
- print('您的购物车里边有:', shopping_cart)
- tag = False
- break
- else:
- print('输入非法, 请重新输入')
- continue
购物车程序代码(购物基本功能)
来源: http://www.bubuko.com/infodetail-2625628.html