当前位置:首页 > 编程技术 > 正文内容

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

yc8881年前 (2023-02-21)编程技术483

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

自动售货机的逻辑

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 中创建自动售货机程序以及主要逻辑的工作原理。


本站发布的内容若侵犯到您的权益,请邮件联系站长删除,我们将及时处理!


从您进入本站开始,已表示您已同意接受本站【免责声明】中的一切条款!


本站大部分下载资源收集于网络,不保证其完整性以及安全性,请下载后自行研究。


本站资源仅供学习和交流使用,版权归原作者所有,请勿商业运营、违法使用和传播!请在下载后24小时之内自觉删除。


若作商业用途,请购买正版,由于未及时购买和付费发生的侵权行为,使用者自行承担,概与本站无关。


本文链接:https://www.10zhan.com/biancheng/10581.html

标签: Python
分享给朋友:

“你如何在 Python 中编写自动售货机代码?” 的相关文章

【说站】laravel实现自定义404页面并给页面传值

【说站】laravel实现自定义404页面并给页面传值

以 laravel5.8 为例,虽然有自带的404页面,但太简单,我们更希望能自定义404页面,将用户留在站点。实现的方式很简单,将自定义的视图文件命名为 404.blade.php,并放到 reso...

【说站】用一句话就可以去除宝塔面板操作上的二次验证

【说站】用一句话就可以去除宝塔面板操作上的二次验证

用过宝塔的朋友应该都会发现,现在宝塔面板有些鸡肋的功能,删除文件、删除数据库、删除站点等操作都需要做计算题!不仅加了几秒的延时等待,还无法跳过!这时候就会有朋友在想,如何去除宝塔面板的二次验证,此篇文...

【说站】Centos8.0如何配置静态IP详解及永久关闭防火墙

【说站】Centos8.0如何配置静态IP详解及永久关闭防火墙

这篇文章主要介绍了详解Centos8 配置静态IP的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来学习一下!1. 查看自己的网关地址点击虚...

【说站】电脑安装MySQL时出现starting the server失败原因及解决方案

【说站】电脑安装MySQL时出现starting the server失败原因及解决方案

今天在安装MySQL时出现starting the server失败,经过查询分析得出以下结论,记录一下操作步骤。原因分析:如果电脑是第一次安装MySQL,一般不会出现这样的报错。如下图所示。star...

【说站】vagrant实现linux虚拟机的安装并配置网络

【说站】vagrant实现linux虚拟机的安装并配置网络

一、VirtualBox的下载和安装1、下载VirtualBox官网下载:https://www.virtualbox.org/wiki/Downloads我的电脑是Windows的,所以下载Wind...

【说站】Java从resources读取文件内容的方法有哪些

【说站】Java从resources读取文件内容的方法有哪些

本文主要介绍的是java读取resource目录下文件的方法,比如这是你的src目录的结构├── main│ ├── java│ │ └── ...