learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022
下載PyCharm,練習用 function 讓程式更簡潔、可讀性更高
(但可以化簡的地方還很多!)
# Coffee Machine
def print_report():
rest_water = resources['water']
rest_milk = resources['milk']
rest_coffee = resources['coffee']
money_in_machine = earn_money
print(f"Water: {rest_water}ml")
print(f"Milk: {rest_milk}ml")
print(f"Coffee: {rest_coffee}g")
print(f"Money: ${money_in_machine}")
def check_resources(coffee_want):
need_water = MENU[coffee_want]['ingredients']['water']
need_milk = MENU[coffee_want]['ingredients']['milk']
need_coffee = MENU[coffee_want]['ingredients']['coffee']
not_enough = []
if resources['water'] >= need_water and resources['milk'] >= need_milk and resources['coffee'] >= need_coffee:
return 'success'
if resources['water'] < need_water:
not_enough.append('water ')
if resources['milk'] < need_milk:
not_enough.append('milk ')
if resources['coffee'] < need_coffee:
not_enough.append('coffee ')
return not_enough
def insert_coin(coffe_want):
quarters = int(input("how many quarters?: "))
dimes = int(input("how many dimes?: "))
nickles = int(input("how many nickles?: "))
pennies = int(input("how many pennies?: "))
insert_money = 0.25 * quarters + 0.1 * dimes + 0.05 * nickles + 0.01 * pennies
if insert_money >= MENU[coffe_want]['cost']:
change = round(insert_money - MENU[coffe_want]['cost'], 2)
print(f"Here is ${change} in change.")
print(f"Here is your {coffe_want}. Enjoy!")
return True
else:
print(f"Sorry that's not enough money. Money refunded.")
return False
machine_working = True
earn_money = 0
while machine_working:
order = input("What would you like? (espresso/latte/cappuccino): ").lower()
if order == 'espresso' or order == 'latte' or order == 'cappuccino':
check_result = check_resources(order)
if check_result == 'success':
if insert_coin(order):
resources['water'] -= MENU[order]['ingredients']['water']
resources['milk'] -= MENU[order]['ingredients']['milk']
resources['coffee'] -= MENU[order]['ingredients']['coffee']
earn_money += MENU[order]['cost']
continue
else:
print(f"Sorry there is not enough {''.join(check_result)}.")
if order == 'report':
print_report()
if order == "off":
machine_working = False