优化(购物项目)

用for循环输出商品名单,其中用了enumerate函数对列表进行格式化输出

#_author:Administrator
#date:2019/10/25
shopping_list=[
('iphone11',5800),
('mac book ',9000),
('coffee ',38),
('python book',80),
('bicycle',1200),
]
saving=input("please input your salary:")
shopping_car=[]

if saving.isdigit():
saving=int(saving)
while True:
#for循环用来打印商品内容
for i,v in enumerate(shopping_list,1):#enumerate()函数自动为每一项添加序号,从0开始,因此步长设置为1

print(i,'----->',v)#用两个变量去接收元组,i和v之间可以加描述符
#引导用户进行输入
chose = input("选择购买商品编号[退出:q]")
#验证输入是否合法
if chose.isdigit():
chose=int(chose)
if chose>0 and chose<=len(shopping_list):
#将用户选择商品通过chose取出来
sh_item=shopping_list[chose-1]
#如果钱够,用本金减去商品价格,并将该商品加入购物车
if sh_item[1]<saving:
saving-=sh_item[1]
shopping_car.append(sh_item)

else:
print('余额不足,你的余额还有%d'%saving)
print(sh_item)

else:
print('编码不存在')
elif chose == "q":
print('---------------------你已经购买如下商品---------------------')
#循环遍历购物车里的商品,购物车里面存放的是已买商品
for i in shopping_car:
print(i)
print('你还剩%d块钱'%saving)
break

else:
print("invalid input")
Output:

please input your salary:1
1 -----> ('iphone11', 5800)
2 -----> ('mac book ', 9000)
3 -----> ('coffee ', 38)
4 -----> ('python book', 80)
5 -----> ('bicycle', 1200)
选择购买商品编号[退出:q]q
---------------------你已经购买如下商品---------------------
你还剩1块钱




posted @ 2019-10-25 19:45  Stary_tx  阅读(175)  评论(0编辑  收藏  举报