파이썬으로 커피 자판기 만들기
에스프레소, 라떼, 카푸치노 3가지 선택지의 커피 머신을 만드는 미니 프로젝트다.
재귀함수, if문, for문 등의 이전까지 배운 내용을 다양하게 활용해 볼 수 있었다.
물, 커피, 우유의 양과 가격이 메뉴별로 다르므로
사용자가 어떤 메뉴를 선택하냐에 따라 여러 가지를 고려해야 한다.

특히 주의해야 할 점은 이 머신이 미국 동전으로 작동한다는 사실인데,
- 페니 1센트
- 니켈 5센트
- 다임 10센트
- 쿼터 25센트
각각 이만큼의 가치를 지닌다.
또한 부가적으로, 현재 머신 내의 재료와 잔돈 여부를 확인할 수 있는
report 기능을 넣어주어야 한다.
머신 작동 순서 정리
- 뼈대 잡기 (메뉴, report, 오타 입력 구분) - if문, 재귀함수
- 재료 충분한지 확인 - for문
- 동전 넣기 > 금액 충분한지 확인 - True, False를 반환하는 함수
- 음료와 잔돈 반환
- 재료와 잔돈 재고 업데이트 - global 선언
- 다음 주문 받기
주어진 데이터
메뉴별 재료와 가격, 자판기의 최대 재료양은 미리 주어진다.
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
profit = 0
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
1. 뼈대 잡기 (메뉴, report, 오타 입력 구분)
메뉴를 묻고, report를 입력하지 않았는지 일차적으로 분류해 준다.
사용자가 오타를 냈을 때 대처할 수 있도록 전체를 재귀함수로 만들어 주었다.
def machine():
choice = input("What would you like? (espresso/latte/cappuccino): ")
choice = choice.lower()
if choice == "espresso" or choice == "latte" or choice == "cappuccino":
if ingrediants_enough(choice):
if money_enough(choice, inserted_money):
elif choice == "report":
report()
else:
print("Please type your order again!")
machine()
machine()
report를 입력했을 경우 report() 함수로 이어진다.
def report():
"""Print currently remained ingrediants and money if you enter 'report'."""
for item in resources:
print(f'{item.title()}: {resources[item]}ml')
print(f'Money: ${profit}')
2. 재료 충분한지 확인
이제 과정에 필요한 함수들을 하나씩 만들어준다.
필요한 재료와 머신 내의 재료를 비교해 줄 check_ingrediants() 함수를 만든다.
메뉴마다 딕셔너리에 저장된 재료 종류가 다르므로
재료를 하나씩 지정해 확인할 경우 에러가 발생할 수 있다.
딕셔너리 안에 있는 재료만 확인해 볼 수 있도록 for문을 이용한다.
조건을 모두 충족할 경우
잔돈과 음료를 반환하는 문장을 출력한다.
def ingrediants_enough(choice):
"""Check if ingrediants are enough."""
menu_ingrediant = MENU[choice]["ingredients"]
for ingrediant in menu_ingrediant:
if menu_ingrediant[ingrediant] > resources[ingrediant]:
print(f'Sorry, there is not enough {ingrediant}.')
return False
return True
3. 동전 넣기 > 금액 충분한지 확인
동전을 받는 insert_coin() 함수와
삽입된 돈이 메뉴를 구입하기에 충분한지 확인하는 money_enough() 함수를 만든다.
_enough() 함수들은 재고 여부에 따라 False 또는 True를 출력하여 if문에 바로 사용할 계획이다.
def insert_coin():
"""Calculate inserted money."""
print("Please insert coins.")
quarter = int(input("how many quarters?: "))
dime = int(input("how many dimes?: "))
nickle = int(input("how many nickles?: "))
penny = int(input("how many pennies?: "))
total = (quarter*25 + dime*10 + nickle*5 + penny) / 100
return total
def money_enough(choice, inserted_money):
menu_cost = MENU[choice]["cost"]
if inserted_money < menu_cost:
print("Sorry, that's not enough money. Money refunded.")
return False
else:
return True
4. 음료와 잔돈 반환
machine() 함수에서 재료와 금액 조건을 모두 충족할 경우
거스름돈과 음료를 내주는 과정을 추가한다.
def machine():
choice = input("What would you like? (espresso/latte/cappuccino): ")
choice = choice.lower()
if choice == "espresso" or choice == "latte" or choice == "cappuccino":
if ingrediants_enough(choice):
inserted_money = insert_coin()
if money_enough(choice, inserted_money):
update_ingrediants(choice)
change = inserted_money - MENU[choice]["cost"]
print(f'Here is ${change} in change.')
print(f'Here is your {choice} ☕️. Enjoy!')
elif choice == "report":
report()
else:
print("Please type your order again!")
machine()
machine()
5. 재료와 잔돈 재고 업데이트
이제 밖으로 보이는 부분은 완성이다.
마지막으로 머신 안의 재고 현황을 음료 판매 후의 상태로 바꿔주어야 한다.
update_ingrediants() 함수를 만들어 준다.
주의할 점은 함수 밖의 전역변수인 MENU와 profit 값을 함수를 이용해 바꿔줄 것이기 때문에
첫 부분에 global 선언을 통해
함수 안의 MENU와 profit이 함수 밖의 변수와 같은 것임을 알려주어야 한다.
def update_ingrediants(choice):
"""Update the current ingrediants and profit."""
global MENU, profit
menu_ingrediant = MENU[choice]["ingredients"]
menu_cost = MENU[choice]["cost"]
for ingrediant in menu_ingrediant:
resources[ingrediant] -= menu_ingrediant[ingrediant]
profit += menu_cost
간단한 파이썬 커피머신 완성!
깃허브에 완성본을 업로드해 두었다.
https://github.com/jihyelisa/python-study/blob/main/python-angela/Day15_coffeeMachine.py
GitHub - jihyelisa/python-study
Contribute to jihyelisa/python-study development by creating an account on GitHub.
github.com
'dev > languages' 카테고리의 다른 글
[Java] '입력 받은' 달의 시작 요일과 마지막 날짜 구하기 (0) | 2023.02.23 |
---|---|
[Java] ArrayList 정렬하기 - Comparable, Comparator 인터페이스의 차이와 Collection.sort() 사용 (0) | 2023.02.17 |