python購物車小程式

來源:互聯網
上載者:User

標籤:%s   current   存在   user   rod   數字   工資   價格   phone   

要求:
1.使用者輸入工資後展示商品列表
2.根據商品編號選擇商品
3.選擇商品後列印商品清單以及剩餘工資
代碼如下:
# coding=utf-8
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)
while True:
for index,item in enumerate(product_list):#enumerate--取下標
print(index,item)#列印商品列表
#取下標print(product_list.index(item),item)
user_choice = input("選擇商品>>>:")
if user_choice.isdigit():#判斷使用者輸入是否為數字
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >=0:#判斷使用者輸入的商品編號是否在下標範圍之內,len()-取列表下標長度
p_item = product_list[user_choice]#通過下標擷取商品價格

if p_item[1] <= salary:#買的起
shopping_list.append(p_item)#將該商品加到購物車
salary -= p_item[1]#扣錢
print("Added %s into shopping cart,your current banlance is \033[31;1m%s\033[0m"%(p_item ,salary))
else:#買不起
print("\033[41;1m你的餘額只剩[%s]啦,買不起啦,你可選擇其他商品或者輸入‘q’退出\033[0m" % salary)
else:#輸入編號不存在
print("商品不存在[%s]",user_choice)

elif user_choice == ‘q‘:#退出
print("---------shopping list----------")#列印商品清單
for p in shopping_list:
print(p)
print("你的工資餘額。。。",salary)
exit()
else:
print("invalid option")

python購物車小程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.