问题描述:
商店有一系列商品,给出购买序列,然后输入你的金额,然后选择要购买的商品序号或是退出,如果持续购买余额不足则提醒用户余额不足,然后如果用户退出则打印用户购买的商品列表,并打印用户余额。
# 购物车程序
product_list = [
('Mac', 9000),
('Kindle', 8000),
('tesla', 900000),
('Python_book', 105),
('bike', 2000),
]
shopping_car = [] # 购物车
money = input('please input your money') # 你的金钱
if money.isdigit():
money = int(money)
# for i in product_list:#方法一:
# print(product_list.index(i)+1,':',i)
#
# for i in enumerate(product_list,1): #方法二: enumerate()带索引的打印 下标从1开始,不加1,默认从0开始。
# print(i)
while True:
for i, v in enumerate(product_list, 1): # 方法三: 方法二 打印的是一个个元组,我们用两个变量i,v接收元组
print(i, v)
choice = input('please input the num[exit:q]')
if choice.isdigit():
choice = int(choice)
if (choice >= 1) and (choice <= len(product_list)): # 求列表的长度
p_item = product_list[choice - 1]
p_price = float(p_item[1])
if p_price < money:
money -= p_price
shopping_car.append(p_item)
else:
print('your money is not enough %s' % money)
print(p_item, p_price)
else:
print('编码不存在!')
elif choice == 'q':
print('您购买的商品如下:')
for i, v in enumerate(shopping_car, 1): # 方法三: 方法二打印的是一个个元组,我们用两个变量i,v接收元组
print(i, v)
print('您还剩余%s元' % money)
break
else:
print('input invalid')
else:
print('your input is not reasonable')
要点: