of the easiest programming languages, and one that encapsulates within itself diversity and the potential to include code as complex as they come. While there are a number of projects and tutorials on beginner-friendly Python-based coding, in this article, we will learn to build a Coffee Machine program in Python. This article will provide an understanding and practice of conditional statements, loops, and Python dictionaries and will serve as a basis for complex coding (in a later article).
Understanding the Project Requirements
First things first, let us try to understand how the program will work, what the basic requirements are, what variables and conditionals we will need, and the scope of the Coffee Making Machine.
The program will function as follows: The program will display menu items and ask the user if they want a drink. The user may choose a drink of their liking.
If the user chooses a drink, we will have to make sure our coffee machine has enough resources to make the coffee. If it has, then we will continue ahead. Otherwise, we will let the user know.
If the resources are enough, then we will ask the user for payment in the form of coins of nickels, pennies, dimes, and quarters. We will calculate the payment made versus the cost. If the payment is complete, we will make the coffee and serve it. If the payment made is more than the price of the coffee, we will give them their change back. Otherwise, if the payment falls short of the price, we will reject the order and give back their coins.
An exception we will add is that if someone from management wants to know the resources left, or the money the machine has stored after completing orders, they may access this by typing ‘report’. Moreover, if the management wants to switch off the machine completely, they may do so by typing ‘off’
Let us define all this with the help of a flowchart:
Step 1: Defining Menu & Resources
The first step in coding this Coffee Machine Project is to define the menu as well as the resources the machine has to prepare any order. In our example, we will have 3 items on the menu: Latte, Espresso, and Cappuccino.
We will use the Python dictionary in order to define the menu variable. A Python dictionary is a useful data type that stores data against a key, both of which are easily accessible. The menu variable will be a dictionary that not only stores the 3 menu items, ie, latte, cappuccino, and espresso, but also describes the ingredients that are required to make them and their price. Let us code the above:
menu = {
"espresso": {
"ingredients": {
"water": 50,
"milk" : 0,
"coffee": 20,
},
"price": 1.5,
},
"latte": {
"ingredients": {
"water": 150,
"milk": 200,
"coffee": 25,
},
"price": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 25,
},
"price": 3.0,
}
}
The next task is to define the resources we have. These are the resources that would be required to make the different types of coffee, as well as the money that is generated by selling the coffee.
resources = {
"water": 1000,
"milk": 1000,
"coffee": 100,
"money": 0
}
As you can see, we have specific amounts of each ingredient as our resources, and 0 money as no coffee has been sold initially.
Step 2: Ask User for Order
The next step is to ask the user what they would like to order. We will use the Python input function for this purpose. Moreover, we will convert the input string to lowercase so it will be easily matched in our conditionals that will follow.
order = input("What would you like to order?\n Cappuccino, Latte or Espresso?\n").lower()
Step 3: Add Special Cases using Conditionals
Next, we will add 2 special cases. The first one is that if the management wants to turn the machine completely off, they will enter off
as input to the above statement, and the machine will turn off, or in other words, the program will end. We will define a variable for this purpose called end
that will be False
initially and will turn True
when the management wants to turn off the machine.
Another case we will add here is when the management would like to know the resources in the coffee machine, they will enter report
, and the machine will print a report of the available resources. Let us put these cases to code:
if order == 'off':
end = True
elif order == 'report':
print(f"We have the following resources:\nWater: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}g \nMoney: ${resources['money']}")
Note that we have used \n
and f-string to properly format the report. Result would be:
Step 4: Check Resources
The next step is to check the resources required to make coffee. If an espresso requires 50ml of water and 20g of coffee, and either of the ingredients is insufficient, we cannot proceed with making coffee. Only when the ingredients are there will we proceed towards making coffee.
This is going to be lengthy to code, we will check one by one whether each of the ingredients are there in our resources:
if resources['water'] >= menu[order]['ingredients']['water']:
if resources['milk'] >= menu[order]['ingredients']['milk']:
if resources['coffee'] >= menu[order]['ingredients']['coffee']:
#We will prepare order
else:
print("\nResources insufficient! There is not enough coffee!\n")
else:
print("\nResources insufficient! There is not enough milk!\n")
else:
print("\nResources insufficient! There is not enough water!\n")
Only when the 3 conditions are checked, then we will proceed with making the coffee; otherwise, print to the user which of the ingredients is not sufficient. Also, we have to make sure that the user has paid the price of their order. Let us do that.
Step 5: Ask and Calculate Payment
For the condition listed above, where all resources are available, the next step is to ask the user to pay the price. Once the payment is done, we will make the coffee.
print(f"Pay ${menu[order]['price']}\n")
Now we will ask the user to insert coins (our coffee machine is outdated, so bear with the clinking of the coins :P). We will ask for the coins they are inserting and calculate the total, then compare it with the price of their order.
Coins inserted in the coffee machine are of 4 different types:
- Pennies = $0.01
- Nickels = $0.05
- Dimes = $0.10
- Quarters = $0.25
The total
value will be calculated by multiplying the number of coin types by their values. Make sure to convert the input into an int type; otherwise, you will have an error.
print("Insert coins")
p = int(input("Insert pennies"))
n = int(input("Insert nickels"))
d = int(input("Insert dimes"))
q = int(input("Insert quarters"))
total = (p * 0.01) + (n * 0.05) + (d * 0.10) + (q * 0.25)
Next, is to check whether the total
amount calculated is equal to the price of the coffee selected or not? Here is how we will code it:
if total == menu[order]['price']:
print("Transaction successful. Here is your coffee!")
elif total > menu[order]['price']:
change = total - menu[order]['price']
print(f"You have inserted extra coins. Here is your change ${change}\n")
else:
print("Payment not complete. Cannot process order")
Only when the amount is equal to the price of the coffee, is the transaction successful. If the total
value is greater than the price, we will need to return the change to the user. Otherwise, if the total value falls short of the price, we will cancel the order.
Step 6: Make Coffee
The last step is to dispense the coffee to the user, and in our coding world, we will do so by updating both the ingredients and the money in our resources dictionary.
if total == menu[order]['price']:
resources['water'] = resources['water'] - menu[order]['ingredients']['water']
resources['coffee'] = resources['coffee'] - menu[order]['ingredients']['coffee']
resources['milk'] = resources['milk'] - menu[order]['ingredients']['milk']
resources['money'] = resources['money'] + menu[order]['price']
print("Transaction successful. Here is your coffee!")
Notice that the ingredients are subtracted from the resources while money is added. Hence, our resources dictionary is updated with each order delivered. The same condition will also be added when we have an additional amount and are required to give change back.
Step 7: Program Continuity
After the coffee order is processed, as long as the management doesn’t command the coffee machine to switch off, the machine will keep on asking the user for their coffee order, processing payments, updating resources, and dispensing the coffee. So we will include a while loop to ensure the program continues after the drink has been dispensed.
The entire block of code we have coded above will be included in this while loop:
while end != True:
order = input("\nWhat would you like to order?\nCappuccino, Latte or Espresso?\n").lower()
if order == 'off':
end = True
elif order == 'report':
print(f"We have the following resources:\nWater: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}g \nMoney: ${resources['money']}")
elif resources['water'] >= menu[order]['ingredients']['water']:
if resources['milk'] >= menu[order]['ingredients']['milk']:
if resources['coffee'] >= menu[order]['ingredients']['coffee']:
print(f"Pay ${menu[order]['price']}\n")
# TODO : Coins insert
print("Insert coins")
p = int(input("Insert pennies"))
n = int(input("Insert nickels"))
d = int(input("Insert dimes"))
q = int(input("Insert quarters"))
total = (p * 0.01) + (n * 0.05) + (d * 0.10) + (q * 0.25)
if total == menu[order]['price']:
resources['water'] = resources['water'] - menu[order]['ingredients']['water']
resources['coffee'] = resources['coffee'] - menu[order]['ingredients']['coffee']
resources['milk'] = resources['milk'] - menu[order]['ingredients']['milk']
resources['money'] = resources['money'] + menu[order]['price']
print("Transaction successful. Here is your coffee!")
elif total > menu[order]['price']:
change = total - menu[order]['price']
print(f"You have inserted extra coins. Here is your change ${change}\n")
else:
print("Payment not complete. Cannot process order")
else:
print("\nResources insufficient! There is not enough coffee!\n")
else:
print("\nResources insufficient! There is not enough milk!\n")
else:
print("\nResources insufficient! There is not enough water!\n")
Conclusion
We have successfully converted the working of a coffee machine into Python code. Over the course of this project, we explored dictionaries and accessing them, conditional statements, and the while loop. While quite straightforward, we can further simplify this project with other techniques such as Object Oriented Programming (a project for next time). Do share your feedback regarding this project and any suggestions on how we can further improve it. Till then, enjoy your coffee!
Access the full code here: https://github.com/MahnoorJaved98/Coffee-Machine/blob/main/Coffee%20Machine%20-%20Python.py
Source link
#Implementing #Coffee #Machine #Python