購物車程序
需求:
. 啓動程序後,讓用戶輸入工資,而後打印商品列表
. 容許用戶根據商品編號購買商品
. 用戶選擇商品後,檢測餘額是否夠,夠就直接扣款,不夠就提醒
.用戶可一直購買商品,也可隨時退出,退出時打印已購的商和餘額git
# 商品列表
product_list = [
('Iphone8', 6888),
('MacPro', 14800),
('小米6', 2499),
('bike', 800),
('Coffee', 31),
('Nike Shoes', 799),
]
# 購物車
shopping_list = []
salary = input("輸入您的薪水:")
if salary.isdigit(): # 檢測字符串是否只由數字組成
salary = int(salary)
run_flag = True
while run_flag:
print(str.center('商品列表', 30, '-'))
for k, v in enumerate(product_list):
print('%s. %s %s' % (k, v[0], v[1]))
choice = input("請輸入想買商品的編號,退出請輸入q:")
if choice.isdigit():
choice = int(choice)
print(choice)
if choice >= 0 and choice < len(product_list):
item_price = product_list[choice]
if item_price[1] <= salary: #買得起
shopping_list.append(item_price) # 追加到購物車
salary -= item_price[1]
print("%s添加到購物車,您當前餘額是:%d" % (item_price, salary))
else:
print('您當前餘額不足')
else:
print('商品不存在')
elif choice == 'q' or choice == 'Q':
if len(shopping_list) > 0:
print(str.center('您已購買如下商品', 30, '-'))
for k, v in enumerate(shopping_list):
print('%s. %s %s' % (k, v[0], v[1]))
print("您當前餘額:%d" % salary)
run_flag = False