如何在Python中編寫一個自動售貨機程式?


在本文中,我們將學習如何用Python編寫一個自動售貨機程式。

Python實現的自動售貨機

每個商品將擁有產品ID、產品名稱和產品成本屬性,這些屬性儲存在一個字典中。還有一個列表,目前為空,稍後將填充所有選擇的商品。

"run"變數的值為True,直到使用者決定滿意不再購買任何商品;此時,該值將變為False,迴圈結束。

現在我們將嘗試瞭解自動售貨機的Python程式碼。

items_data = [
   {
      "itemId": 0,
      "itemName": "Dairymilk",
      'itemCost': 120,
   },{
      "itemId": 1,
      "itemName": "5star",
      'itemCost': 30,
   },{
      "itemId": 2,
      "itemName": "perk",
      'itemCost': 50,
   },{
      "itemId": 3,
      "itemName": "Burger",
      'itemCost': 200,
   },{
      "itemId": 4,
      "itemName": "Pizza",
      'itemCost': 300,
   },
]

item = []

bill = """
\t\tPRODUCT -- COST
"""
sum = 0
run = True

列印選單

編寫了一個簡單直接的迴圈來列印自動售貨機的選單以及每個商品的必要屬性。

print("------- Vending Machine Program with Python-------\n\n")
print("----------Items Data----------\n\n")

for item in items_data:
   print(f"Item: {item['itemName']} --- Cost: {item['itemCost']} --- Item ID: {item['itemId']}")

計算總價

建立了一個名為sum()的函式,它迭代所有選擇的待購商品列表。在迴圈遍歷列表並將product_cost屬性新增到總計後,該函式將返回總金額。

def sumItem(item):
   sumItems = 0
   for i in item:
      sumItems += i["itemPrice"]
   return sumItems

自動售貨機的邏輯

在自動售貨機中編寫了Python程式的主要函式Machine()。此函式將接受三個引數:items_data字典、布林值的run變數以及包含使用者所需所有商品的item列表。使用while迴圈,但它僅在run變數的值為True時才有效。

此處必須輸入所需商品的產品ID。如果產品ID小於**items_data**字典的總長度,則必須將所有id屬性新增到商品列表中;否則,將列印訊息**“錯誤的產品ID”**。如果使用者拒絕,則run變數將變為False,並提示他們新增更多商品。系統將提示您是否要列印整個賬單或僅列印總金額。

def vendingMachine(items_data, run, item):
   while run:
      buyItem = int(
         input("\n\nEnter the item code for the item you want to buy: "))
      if buyItem < len(items_data):
         item.append(items_data[buyItem])
      else:
         print("THE PRODUCT ID IS WRONG!")
      moreItems = str(
         input("type any key to add more things, and type q to stop:  "))
      if moreItems == "q":
         run = False
   receiptValue = int(
      input(("1. Print the bill? 2. Only print the total sum: ")))
   if receiptValue == 1:
      print(createReceipt(item, reciept))
   elif receiptValue == 2:
      print(sumItem(item))
   else:
      print("INVALID")

建立賬單的函式

Python實現的自動售貨機的另一個功能是在控制檯上建立賬單顯示。函式**create_bill()**將接受兩個引數:

  • 選擇的商品的**item**列表

  • **bill**,這是一個樣板選單字串,並且已被選中。

在迭代item列表時選擇商品的名稱和價格,並列印必要的資訊。最後,這段程式碼將再次使用之前的**sum**()函式輸出總成本。

請記住,此**create_bill**()方法是在**sum**()函式之外獨立建立的。

def create_bill(item, bill):

   for i in item:
      bill += f"""
      \t{i["itemName"]} -- {i['itemCost']}
      """

   bill += f"""
      \tTotal Sum --- {sum(item)}        
        
      """
   return bill

完整的Python自動售貨機程式碼

示例

以下是使用python建立自動售貨機的所有步驟的完整程式碼:

items_data = [
   {
      "itemId": 0,
      "itemName": "Dairy Milk",
      'itemPrice': 120,
   },{
      "itemId": 1,
      "itemName": "5Star",
      'itemPrice': 30,
   },{
      "itemId": 2,
      "itemName": "perk",
      'itemPrice': 50,
   },{
      "itemId": 3,
      "itemName": "Burger",
      'itemPrice': 200,
   },{
      "itemId": 4,
      "itemName": "Pizza",
      'itemPrice': 300,
   },
]
item = []
reciept = """
\t\tPRODUCT NAME -- COST
"""
sum = 0
run = True

print("------- Vending Machine Program with Python-------\n\n")
print("----------The Items In Stock Are----------\n\n")


for i in items_data:
   print(
      f"Item: {i['itemName']} --- Price: {i['itemPrice']} --- Item ID: {i['itemId']}")


def vendingMachine(items_data, run, item):
   while run:
      buyItem = int(
         input("\n\nEnter the item code for the item you want to buy: "))
      if buyItem < len(items_data):
         item.append(items_data[buyItem])
      else:
         print("THE PRODUCT ID IS WRONG!")
      moreItems = str(
         input("type any key to add more things, and type q to stop:  "))
      if moreItems == "q":
         run = False
   receiptValue = int(
      input(("1. Print the bill? 2. Only print the total sum: ")))
   if receiptValue == 1:
      print(createReceipt(item, reciept))
   elif receiptValue == 2:
      print(sumItem(item))
   else:
      print("INVALID")


def sumItem(item):
   sumItems = 0
   for i in item:
      sumItems += i["itemPrice"]
   return sumItems


def createReceipt(item, reciept):
   for i in item:
      reciept += f"""
      \t{i["itemName"]} -- {i['itemPrice']}
      """
   reciept += f"""
      \tTotal --- {sumItem(item)}
      """
   return reciept


# Main Code
vendingMachine(items_data, run, item)

輸出

------- Vending Machine Program with Python-------


----------The Items In Stock Are----------


Item: Dairy Milk --- Price: 120 --- Item ID: 0
Item: 5Star --- Price: 30 --- Item ID: 1
Item: perk --- Price: 50 --- Item ID: 2
Item: Burger --- Price: 200 --- Item ID: 3
Item: Pizza --- Price: 300 --- Item ID: 4


Enter the item code for the item you want to buy: 2
type any key to add more things, and type q to stop:  t


Enter the item code for the item you want to buy: 3
type any key to add more things, and type q to stop:  q
1. Print the bill? 2. Only print the total sum: 1

		PRODUCT NAME -- COST

        	perk -- 50
        
        	Burger -- 200
        
        	Total --- 250

結論

在本文中,我們學習瞭如何在Python中建立自動售貨機程式以及主要邏輯的詳細工作原理。

更新於:2023年1月31日

7000+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.