python雜記-3(購買商品),python-3

來源:互聯網
上載者:User

python雜記-3(購買商品),python-3

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#如下是一個購物程式:
#先輸入工資,顯示商品列表,購買,quit退出,最後格式化輸出所買的商品。
count = 0
while True: #做一個迴圈判斷,如果輸入的不是數字,基於提示,三次後退出
salary = input("input your salary:") #輸入你的工資
if salary.isdigit(): #輸入的工資必須是數字才能往下走
salary=int(salary) #轉換為整數型
break
else:
print("Please input a number:")
count += 1
if count == 3:
exit()

goods_list = [["Iphone",5800],["Macbook",12800],["iMac",15000],["ApplePen",500],["IPod",1200]] #商品列表
shop_list = [] #購買的商品列表
msg = " Product List "
print(msg.center(30,"*"))
for i,ele in enumerate(goods_list): #遍曆序列中的元素以及它們的下標
print(i,".",ele[0],ele[1])
while True:
choice = input("Which do you want(quit type \"quit\")>>>")
if choice.isdigit(): #判斷選擇的是否是數字
choice = int(choice) #轉換為整數型
if choice <= len(goods_list)-1: #選擇的數字必須小於列表長度-1,因為下標從0開始
if salary >= int(goods_list[choice][1]): #判斷工資是否夠
shop_list.append(goods_list[choice]) #夠的話,把商品加入到shopList
salary -= goods_list[choice][1] #減去工資
print("You just buy a %s now you have %s RMB" % (goods_list[choice][0],salary))
else:
print("Not enough money")
else:
print("There is no such things")
elif choice == "quit":
print("Here is what you buy:") #這裡的思路是,建立一個字典,把所買的商品格式化輸出
total = 0
shop_dict={}
for item in shop_list:
things = item[0]
money = item[1]
total += int(money)
if things in shop_dict:
shop_dict[things][0] += 1
shop_dict[things][1] += money
else:
shop_dict[things]=[1,money]
for item in shop_dict.items():
print("%s %s個 共%s" % (item[0],item[1][0],item[1][1]))
print("一共花了:",total)
exit()
else:
print("Please input a number")
continue

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.