雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

你如何在 Python 中编写自动售货机代码?

2024-08-19 29

在本文中,我们将学习用 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

自动售货机的逻辑

Machine(),Python程序的主要功能,写在自动售货机中。此函数将接受的三个参数是items_data字典、具有布尔值的运行变量和项目列表,其中包括用户所需的所有项目。但是,使用 while 循环,它仅在运行变量的值为 True 时才起作用。

必须在此处输入所需商品的产品 ID。如果产品 id 小于字典items_data的总长度,则必须将整组 id 属性添加到项目列表中;否则,将打印消息“错误的产品 ID”。如果用户拒绝,则运行变量将更改为 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() 将接受两个参数 -

所选产品的项目列表

该法案是一串样板菜单,已被选中。

在循环访问物料列表时,将选择物料的名称和价格,并打印必要的信息。最后,此代码将再次使用前面的 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 中创建自动售货机程序以及主要逻辑的工作原理。

更新于:28天前
赞一波!2

文章评论

全部评论