
IDE(Integrated Development Environment), 통합 개발 환경
파이썬에 특화된 IDE
(여태까지 사용한 replit처럼 간단한 텍스트 편집기로는 부족하기 때문에 앞으로 파이참으로 진행)
python -V, python --versionwhich pythonProcess finished with exit code 0 가 뜨면 성공| shortcut | action |
|---|---|
| Double ⇧Shift | Quickly find any file, action, class, symbol, tool window, or setting in PyCharm, in your project, and in the current Git repository. |
| ⌘Сmd + ⇧Shift + A | Find a command and execute it, open a tool window, or search for a setting |
| ⌥Opt + ↩Enter | Quick-fixes for highlighted errors and warnings, intention actions for improving and optimizing your code. |
| F2 ⇧Shift + F2 | Jump to the next highlighted error Jump to the previous highlighted error |
| ⌘Сmd + E | Select a recently opened file from the list |
| ⌥Opt + ↑ ⌥Opt + ↓ | Extend selection Shrink selection |
| ⌘Сmd + / ⌘Сmd + ⌥Opt + / | Add/remove line or block comment Comment out a line or block of code |
| ⌥Opt + F7 | Find Usages Show all places where a code element is used across your project |
| ⌥Opt + ⇧Shift + drag | Multiple cursors(select ranges by dragging) |
Split and Move Right/DownLocal History → Show HistoryStructure 클릭 → 원하는 개체의 위치로 바로 이동, 편집 가능Refactor → Rename → Do RefactorEdit → Find → Replace# TODO 내용 작성, # TODO 내용 작성,...🔍 유의 사항
- 구현할 기능
- 에스프레소, 라떼, 카푸치노를 만들어야 함 → 딕셔너리에 메뉴 정보 저장됨
- Espresso($1.50) : 50ml water, 18g coffee
- Latte($2.50) : 200ml water, 24g coffee, 150ml milk
- Cappuchino($3.00) : 250ml water, 24g coffee, 100ml milk
- 커피 자판기에 물 300ml, 우유 200ml, 커피 원두 100g을 채워야 함
- 미국 동전을 넣어서 사용
- Penny : 1 cent → $0.01
- Nickel : 5 cents → $0.05
- Dime : 10 cents → $0.10
- Quater : 25 cents → $0.25
- 요구 사항
- 머신 조작(입력창에 키워드 입력)
→ 동작이 끝난 후, 다음 고객을 위해 입력창이 다시 떠야 함
- report : 현재 머신에 남은 재고와 쌓인 금액에 대한 리포트 출력
- 커피 이름 : 커피 주문
- off : 머신 끄기(코드 종료)
- 커피를 주문하면 남은 재료의 양을 파악 후 해당 커피의 레시피와 대조하여 확인
- 재료가 충분하면, 돈을 받는 단계로 넘어감
- 재료가 부족하면, 어떤 재료가 부족해서 커피를 만들 수 없는지 피드백
- 동전 처리
- 동전을 종류별로 몇 개씩 넣는지 차례로 확인 후, 총 금액 계산
- 거래 과정이 정상적인지 판단
- 돈을 적게 넣었을 경우, 넣은 돈을 전부 반환하고 주문 중단
- 돈을 충분히 넣었을 경우, 보고서에 커피 값이 반영되고 주문 진행
- 만약 커피 값보다 많은 돈이 들어왔으면, 거스름돈 반환
- 거스름돈은 소수점 둘째자리까지 반올림
- 커피 제작
- 커피를 성공적으로 제작하면 남은 재고도 수정되어야 함
- 커피 이모지(☕)와 함께 주문한 커피가 준비되었음을 알리는 문구를 출력하며 종료
⌨️ 작성한 코드
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,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
profit = 0
def report(save):
print(f"Water: {resources["water"]}ml")
print(f"Milk: {resources["milk"]}ml")
print(f"Coffee: {resources["coffee"]}g")
print(f"money: ${save}")
def check_amount(order):
amount_water = True
amount_milk = True
amount_coffee = True
if MENU[order]["ingredients"]["water"] > resources["water"]:
print("Sorry there is not enough water.")
amount_water = False
if order != "espresso":
if MENU[order]["ingredients"]["milk"] > resources["milk"]:
print("Sorry there is not enough milk.")
amount_milk = False
if MENU[order]["ingredients"]["coffee"] > resources["coffee"]:
print("Sorry there is not enough coffee.")
amount_coffee = False
if amount_water is True and amount_milk is True and amount_coffee is True:
return 'yes'
else:
return 'no'
def coin_count(order):
print("please insert coins.")
quarter = float(input("How many quarters?: "))
dime = float(input("How many dimes?: "))
nickle = float(input("How many nickles?: "))
penny = float(input("How many pennies?: "))
total = round((quarter * 0.25) + (dime * 0.10) + (nickle * 0.05) + (penny * 0.01), 2)
if total < MENU[order]["cost"]:
print(f"Sorry ${format(total, '.2f')} is not enough money. Money refunded.")
return 0
elif total >= MENU[order]["cost"]:
if total > MENU[order]["cost"]:
changes = total - MENU[order]["cost"]
print(f"Here is ${round(changes, 3)} in change.")
return MENU[order]["cost"]
else:
return 0
def coffee_make(order):
print(f"Here is your {order} ☕️ Enjoy!")
resources["water"] -= MENU[order]["ingredients"]["water"]
if order != "espresso":
resources["milk"] -= MENU[order]["ingredients"]["milk"]
resources["coffee"] -= MENU[order]["ingredients"]["coffee"]
def use(save):
operation = input("What would you like? (espresso/latte/cappuccino): ").lower()
# 보고서 출력
if operation == 'report':
report(save)
# 커피 주문
elif operation == 'espresso' or operation == 'latte' or operation == 'cappuccino':
# 재고 체크
should_continue_order = check_amount(operation)
if should_continue_order == 'no':
return save
# 투입 금액 체크
coins = coin_count(operation)
if coins == MENU[operation]["cost"]:
save += coins
# 재고와 투입 금액이 모두 만족되면 커피 제조 후 재고 변경
coffee_make(operation)
return save
else:
return save
# 머신 끄기
elif operation == 'off':
print("The machine is shut down.")
return 'off'
else:
print("You typed a wrong keyword.")
machine_on = True
while machine_on:
result = use(profit)
if result == 'off':
machine_on = False
else:
profit = result
[ 출력 결과 ]
What would you like? (espresso/latte/cappuccino): ❚latte
please insert coins.
How many quarters?: ❚10
How many dimes?: ❚10
How many nickles?: ❚10
How many pennies?: ❚1
Here is $1.51 in change.
Here is your latte ☕️ Enjoy!
What would you like? (espresso/latte/cappuccino): ❚espresso
please insert coins.
How many quarters?: ❚8
How many dimes?: ❚4
How many nickles?: ❚6
How many pennies?: ❚2
Here is $1.22 in change.
Here is your espresso ☕️ Enjoy!
What would you like? (espresso/latte/cappuccino): ❚cappuccino
Sorry there is not enough water.
Sorry there is not enough milk.
What would you like? (espresso/latte/cappuccino): ❚report
Water: 50ml
Milk: 50ml
Coffee: 58g
money: $4.0
What would you like? (espresso/latte/cappuccino): ❚off
The machine is shut down.
🖍️ 답안
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,
}
def is_resource_sufficient(order_ingredients):
"""Returns True when order can be made,
False if ingredients are insufficient."""
for item in order_ingredients:
if order_ingredients[item] > resources[item]:
print(f"Sorry there is not enough {item}.")
return False
return True
def process_coins():
"""Returns the total calculated from coins inserted."""
print("Please insert coins.")
total = int(input("how many quarters?: ")) * 0.25
total += int(input("how many dimes?: ")) * 0.1
total += int(input("how many nickles?: ")) * 0.05
total += int(input("how many pennies?: ")) * 0.01
return total
def is_transaction_successful(money_received, drink_cost):
"""Return True when the payment is accepted,
or False if money is insufficient."""
if money_received >= drink_cost:
change = round(money_received - drink_cost, 2)
print(f"Here is ${change} in change.")
global profit
profit += drink_cost
return True
else:
print("Sorry that's not enough money. Money refunded.")
return False
def make_coffee(drink_name, order_ingredients):
"""Deduct the required ingredients from the resources."""
for item in order_ingredients:
resources[item] -= order_ingredients[item]
print(f"Here is your {drink_name} ☕️. Enjoy!")
is_on = True
while is_on:
choice = input("What would you like?(espresso/latte/cappuccino):")
if choice == "off":
is_on = False
elif choice == "report":
print(f"Water: {resources['water']}ml")
print(f"Milk: {resources['milk']}ml")
print(f"Coffee: {resources['coffee']}g")
print(f"Money: ${profit}")
else:
drink = MENU[choice]
if is_resource_sufficient(drink["ingredients"]):
payment = process_coins()
if is_transaction_successful(payment, drink["cost"]):
make_coffee(choice, drink["ingredients"])