iT邦幫忙

0

新手python買東西的問題

  • 分享至 

  • xImage

服飾店買東西,衣服600,褲子500,裙子700,且衣服3件打9折
請問各位,該如何寫出一個可以計算出購買數量且可以合計消費金額的程式

感謝

算了--不想唸了。跳過。刪文
辛苦熱心的菩薩的了 感恩感恩 南無阿彌陀佛
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
4
Peter
iT邦新手 4 級 ‧ 2022-03-18 09:50:08
最佳解答
  1. 我會開2個dict,一個放產品的價格,一個放當前購物車裡的物品數量,例如:
dict_product = {'褲子':600, ...}
dict_cart    = {'褲子':0, '衣服':0, ...}
  1. 設計一個function控制cart的加減,例如:
    (補充:產品名稱用代號可能會更方便,但上面的dict結構要調整一下)
# 注意,簡單範例只假設輸入一次買一件,並且沒有防呆機制
while True:
    product = input('請輸入你要購買的產品名稱, 或輸入 q 結束購買')
    
    # 離開迴圈結束購買
    if product == 'q':
        break 
        
    # 購物車 +1
    dict_cart[product] += 1 
  1. 設計一個function計算總價(針對特價的部分要有if),例如:
# dict_product 與 dict_cart 進行mapping

# 存放總價
total = 0 

# 取出產品來匹配
for i in dict_product.keys():

    # 針對特價做例外處理
    if i == '衣服' and dict_cart[i]>=3:
        sub_total = 0 # 例外計算的總價
        quo = dict_cart[i]//3 # 商數
        rem = dict_cart[i]%3  # 餘數
   
        # 取商數以打折計算
        sub_total += dict_product[i] * quo *3 *0.9
        # 取餘數以原價計算
        sub_total += dict_product[i] * rem
        
        # 最後加總
        total += sub_total
        
        # 跳至迴圈下一步(會跳過一般計算金額,避免重複加總)
        continue
        
    # 一般計算金額
    total += dict_product[i] * dict_cart[i]

以上只是簡易實現,沒有考量到效能或其他控制功能,僅供參考

4
海綿寶寶
iT邦大神 1 級 ‧ 2022-03-18 08:36:37

可以拿這篇去改

話說
你買的衣服比較貴一點
/images/emoticon/emoticon44.gif

3
熊熊工程師
iT邦研究生 2 級 ‧ 2022-03-18 09:19:26

參考用

product = {"clothes": 600, "pants": 500, "skirts": 700}
total = []

for product, price in product.items():
    amount = int(input(f"請輸入 {product} 購買數量: "))
    
    if product == "clothes" and amount >= 3:
        total.append(price * amount * 0.9)
    else:
        total.append(price * amount)

print(f"一共消費 {sum(total)} 元")
Peter iT邦新手 4 級 ‧ 2022-03-18 09:53:45 檢舉

跟我想得差不多,但有一個點是 amount >= 3 可能會遇到買4件其實只有3件的部分打折(通常服飾店好像都這樣),所以我用商數餘數分開算

0
b97203005
iT邦新手 5 級 ‧ 2022-04-16 20:33:41

可以設定X為買clothes的數量, Y為價格

if X>=3:
Y=X x 600 x 0.9

以這樣去算。

我要發表回答

立即登入回答