Python 如何编写自动售货机的代码
在本文中,我们将学习如何在Python中编写自动售货机的代码。
Python实现的自动售货机
每个物品都有其产品编号,产品名称和产品成本属性存储在一个字典中,一个目前为空的列表,但随后将被填充有选择的所有物品。
一个名为”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()的函数,该函数迭代遍历所有选择的购买项目列表。在循环遍历列表并将产品成本属性添加到总金额后,函数将返回总金额。
def sumItem(item):
sumItems = 0
for i in item:
sumItems += i["itemPrice"]
return sumItems
自动售货机的逻辑
Machine(),Python程序的主要函数,写在自动售货机中。这个函数将接受三个参数:items_data字典、布尔值的run变量和包含用户所需所有物品的物品列表。使用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
在遍历项目列表时,选择项目的名称和价格,并打印所需信息。最后,这段代码将再次使用之前的 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创建自动售货机程序,以及主要逻辑的详细工作原理。