需求如下:
代码:
# 购物车的实现
goods = ['Mac 笔记本','自行车','python book','衣服','鞋子']
price = [8000,1500,80,200,360]
car = []
# 请用户输入薪资
salary = int(input('Input your salary:'))
yue = salary
# 展示商品列表
print('你可以选购以下产品:')
for index in range(len(goods)):
print()
print('%d:%s 价格:%d' % (index+1,goods[index],price[index]))
print('输入wq则退出购物')
print()
flag = True
while flag:
chose_num = input('请输入:')
if chose_num == 'wq':
flag = False
print('你购物车的产品为:')
for x in car:
print(x)
print('\n当前你的余额为:%d \n欢迎下次光临!' % (yue))
break
elif chose_num == '':
continue
elif int(chose_num) > len(goods):
print('你输入的产品序号不存在')
else:
# 查找该产品的价格
goods_price = price[int(chose_num)-1]
if yue - goods_price > 0:
car.append(goods[int(chose_num)-1])
# 计算余额
yue = yue - goods_price
print('加入购物车成功 余额为:%d' % (yue))
else:
print('余额不足: %d元' % (salary-goods_price))
效果图如下: