'''
程序練習
購物車程序
需求:
1、啓動程序後,讓用戶輸入工資,然後打印尚品列表
2、允許用戶更加尚品編號購買商品
3、用戶選擇商品後,檢測餘額是否夠,夠就直接扣款,不夠就提醒
4、可隨時退出,退出時,打印已經購買的商品和餘額
'''
product_list = [
('iphone',5800),
('mac pro',9800),
('bike',800),
('watch', 10600),
('coffee', 31),
('alex python', 120)
]
shopping_list = []
salary = input('input your salary:') #輸入工資
if salary.isdigit(): #判斷工資是否是數字
salary = int(salary) #如果是數字給他int
while True:
for index,item in enumerate(product_list): #打印商品列表(enumerate的意思是把下標取出來)
#print(product_list.index(item),item)
print(index,item)
user_choice = input('選擇要買啥?>>>:')
if user_choice.isdigit(): #判斷用戶輸入是數字類型
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >=0: #判斷用戶商品編號
p_item = product_list[user_choice] #通過下標把商品取出來
if p_item[1] <= salary: #買的起
shopping_list.append(p_item) #添加到商品list裏面
salary -= p_item[1] #扣錢
print('added %s into shopping cart,your current balance is \033[31;1m%s\033[0m '%(p_item),salary) #打印一下
else:
print('\033[41;1m你的餘額只剩[%s]啦,還買個毛線\033[0m'%salary) #輸入的商品序號不存在
else:
print('product code [%s] is not exist'% user_choice)
elif user_choice == 'q':
print('-----shopping list-----')
for p in shopping_list:
print(p)
print('your current balance:',salary)
exit()
else:
print('invalid option')
Python學習之購物車程序練習
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.