如何在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.