这是「Python 100 天」系列第 15 天的学习笔记:本地环境与过程式重构:咖啡机 。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。
今天要解决的问题
一个命令行咖啡机:选饮品 → 检查原料够不够 → 收硬币 → 找零 → 扣原料 → 记账,输入 report 看库存和营业额,off 关机。README 只写了"在本机安装 Python",真正的重点是把一段流程拆成若干函数 。
一、在本机跑起来
macOS / Linux 一般自带 python3:
1 2 3 python3 --version cd day15 python3 main.py
Windows 装 python.org 的安装包时勾选 "Add Python to PATH",命令是 python。不要 用 python2,本课程全部是 Python 3 语法。
二、嵌套字典:用数据描述业务
1 2 3 4 5 6 7 MENU = { "espresso": { "ingredients": {"water": 50, "coffee": 18}, "cost": 1.5, }, ... }
三层结构:菜单 → 饮品 → (原料字典, 价格)。访问就是一路下标:
1 2 MENU["latte"]["ingredients"]["milk"] # 150 MENU["latte"]["cost"] # 2.5
resources 和 money 是可变的全局状态 ,所有函数都在改它们。这是这一版的核心问题,也是 Day 16 要用"类"来解决的动因。
三、用字典当"可变单例"
1 2 3 money = {"value": 0} ... money['value'] += MENU[choice]['cost']
为什么不用 money = 0 + global money?因为字典是可变对象,函数里改它的内容 不需要 global 声明。这是一个常见技巧,但不如类清晰。
代码全文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 # ============================================================ # day15/main.py —— 咖啡机(Coffee Machine,过程式版本) # 作用:模拟一台咖啡机:看菜单、查库存、收硬币、找零、出货。 # 知识点:嵌套字典、多行字典字面量、函数拆分、全局变量原地修改、round() # 运行:python main.py # ============================================================ # MENU 是“嵌套字典”:外层键是饮品名,值是另一本字典, # 里面再分 "ingredients"(配方,又一本字典)和 "cost"(价格)。 # 取值链路就是 MENU["latte"]["ingredients"]["water"] → 200。 # 末尾的逗号可有可无,但每行都写,后续增删条目不会因为漏逗号报错。 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, } } # 机器当前库存(单位:水/奶 ml,咖啡豆 g)。 resources = { "water": 300, "milk": 200, "coffee": 100, } # 为什么钱要包一层字典?因为 int 是不可变类型, # 函数里 money += x 只会改局部变量;用字典 money["value"] += x 改的是字典内容, # 不需要 global 声明就能让所有函数看到变化。 money = { "value": 0, } # 打印库存报表。无参数、无返回值(只输出)。 def report(): # f-string 里可以用单引号包字符串键,外层用双引号,避免转义。 print(f"Water: {resources['water']}ml") print(f"Milk: {resources['milk']}ml") print(f"Coffee: {resources['coffee']}g") print(f"Money: ${money['value']}") # 检查库存够不够做这杯咖啡。 # 参数 coffee_choice:饮品名("espresso" / "latte" / "cappuccino") # 返回值:True 表示原料足够,False 表示至少缺一种 def check_resources(coffee_choice): # 先假设够,逐项检查,只要有一样不够就翻成 False——典型的“乐观标记法”。 enough = True # MENU[coffee_choice]["ingredients"]["water"]:先按名字取配方,再取用水量 if MENU[coffee_choice]['ingredients']['water'] > resources['water']: print(f"There isn't enough water for a {coffee_choice}.") enough = False if MENU[coffee_choice]['ingredients']['coffee'] > resources['coffee']: print(f"There isn't enough coffee for a {coffee_choice}.") enough = False # espresso 配方里没有 milk 这一项,直接取会 KeyError,所以先判断是不是 espresso。 if coffee_choice != 'espresso': if MENU[coffee_choice]['ingredients']['milk'] > resources['milk']: print(f"There isn't enough milk for a {coffee_choice}.") enough = False return enough # 把硬币换算成美元总额。 # quarter(25 美分)/ dime(10 美分)/ nickle(5 美分)/ penny(1 美分) # 参数都是“枚数”(int),返回值是总金额(float) # *= 是“原地乘”:quarter = quarter * 0.25,省一次重复写变量名。 def process_coins(quarter, dime, nickle, penny): quarter *= 0.25 dime *= 0.10 nickle *= 0.05 penny *= 0.01 total = quarter + dime + nickle + penny return total # 扣减原料。无返回值,直接改全局 resources 字典里的值。 def deduct_resources(coffee_choice): resources['water'] -= MENU[coffee_choice]['ingredients']['water'] resources['coffee'] -= MENU[coffee_choice]['ingredients']['coffee'] if coffee_choice != 'espresso': resources['milk'] -= MENU[coffee_choice]['ingredients']['milk'] # 主循环:读指令 → 分发处理。 def coffee_machine(): on = True while on: choice = input("What would you like? Type 'espresso', 'latte', 'cappuccino': ") if choice == 'report': report() # 这里又递归调用了一次 coffee_machine(),导致“两层循环”同时在跑: # 返回后外层 while 还会继续,关机器要关好几层。直接写 continue 更干净。 coffee_machine() elif choice == 'off': print("Turning off.") on = False elif check_resources(choice): # 注意 check_resources(choice) 直接当条件用: # 返回 False 时这一支不执行,也不会给出“饮品不存在”的提示(输入乱码会 KeyError)。 print("Please insert coins.") quarters = int(input("How many quarters?: ")) dimes = int(input("How many dimes?: ")) nickles = int(input("How many nickles?: ")) pennies = int(input("How many pennies?: ")) # 三次调用 process_coins 算同一个总额,属于重复计算, # 应该先 paid = process_coins(...) 再比较。 if process_coins(quarters, dimes, nickles, pennies) == MENU[choice]['cost']: deduct_resources(choice) money['value'] += MENU[choice]['cost'] print(f"Here is your {choice} ☕. Have a good one!") elif process_coins(quarters, dimes, nickles, pennies) > MENU[choice]['cost']: deduct_resources(choice) money['value'] += MENU[choice]['cost'] change = process_coins(quarters, dimes, nickles, pennies) - MENU[choice]['cost'] # round(x, n):内置函数,把 x 四舍五入到 n 位小数,返回 float。 # 参数 x:数字;参数 n:保留几位小数,省略则取整。 # 浮点数 0.1+0.2 会得到 0.30000000000000004,所以金额必须 round。 change = round(change, 2) print(f"Here is ${change} in change.") print(f"Here is your {choice} ☕. Have a good one!") else: print(f"Not enough money, ${(process_coins(quarters, dimes, nickles, pennies))} refunded.") # 入口 coffee_machine()
代码走读
report():打印水、奶、咖啡、营业额。
check_resources(coffee_choice):逐个原料比较"配方需要" vs "库存剩余",任一不足就打印提示并返回 False。注意意式浓缩没有牛奶,所以用 if coffee_choice != 'espresso' 跳过奶的检查。
process_coins(quarter, dime, nickle, penny):把硬币数量换算成金额求和。
deduct_resources():扣库存,同样跳过浓缩的牛奶。
coffee_machine():主循环。report 分支里调用 coffee_machine() 递归重开;off 分支把 on 设 False;否则检查原料 → 收钱 → 判断金额。
金额三种情况:正好、多了找零、少了退款。
这份代码的问题清单
(1) 价格比较用 == 和 > 判断浮点数
1 if process_coins(...) == MENU[choice]['cost']:
0.1 + 0.2 != 0.3 是浮点数的经典问题。正确做法是比较"分"(整数)或允许误差:abs(paid - cost) < 1e-9。
(2) 非法饮品名直接 KeyError
choice 不在 MENU 里(比如输入 tea),check_resources 第一行就崩。应先校验 if choice not in MENU。
(3) report 分支用递归
每次看报表就多一层调用,看 50 次就是 50 层。应该 continue 回到循环开头。
(4) process_coins 被调用三次
同一笔钱算了三遍。应该先存进变量:paid = process_coins(...)。
运行示例
1 2 3 4 5 6 7 8 What would you like? Type 'espresso', 'latte', 'cappuccino': latte Please insert coins. How many quarters?: 10 How many dimes?: 0 How many nickles?: 0 How many pennies?: 0 Here is $0.0 in change. Here is your latte ☕. Have a good one!
易错点
原料键名不一致 :"coffee" 写成 "Coffee" 直接 KeyError。
忘了跳过浓缩的牛奶 :MENU['espresso']['ingredients']['milk'] 不存在。
钱扣了但没扣原料 ,或者反过来——顺序应当"扣原料 → 加钱 → 出货"。
全局状态被多处修改 :resources 在三个函数里都被改,排查问题时很难定位。
动手改
用整数"分"重写金额计算,彻底避开浮点误差。
把递归的 report 改成 continue。
把 resources、money 收进一个 Machine 类(预习 Day 16)。
源文件逐个讲解
3 个文件 :main.py(108 行)、README.md(6 行)、Coffee Machine Program Requirements.pdf(69KB,课程给的需求文档,二进制,这里不拆)。
main.py(108 行)——一天里塞了 6 个部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 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, } }
三层嵌套字典 :MENU[品类]['ingredients'][原料]。espresso 没有 milk 键 ——这就带来后面「要不要单独判断咖啡种类」的麻烦。
1 2 resources = {"water": 300, "milk": 200, "coffee": 100} money = {"value": 0}
resources 是库存(毫升/克),money 用单键字典 包了一层。为什么不用普通变量 money = 0?因为函数里要修改它,普通变量得写 global money;而 money['value'] += x 是改字典内容 ,不需要 global。这是用可变对象绕开全局变量声明的技巧 ,能跑,但不如 global 清楚。
四个函数 :
1 2 3 4 5 6 7 8 9 10 def check_resources(coffee_choice): enough = True if MENU[coffee_choice]['ingredients']['water'] > resources['water']: print(f"There isn't enough water for a {coffee_choice}.") enough = False ... if coffee_choice != 'espresso': if MENU[coffee_choice]['ingredients']['milk'] > resources['milk']: ... return enough
用 enough 标志位而不是提前 return False ,好处是把所有缺料一次报全 (水、咖啡、牛奶都缺就打印三条)。这是「累加式校验」的写法。
if coffee_choice != 'espresso' 是因为 espresso 的 ingredients 里没有 milk 键 ——直接 MENU[coffee_choice]['ingredients']['milk'] 会 KeyError。正确的解法是 dict.get('milk', 0),那样就不用特判。
1 2 3 4 5 def process_coins(quarter, dime, nickle, penny): quarter *= 0.25 ... total = quarter + dime + nickle + penny return total
参数复用 :把「数量」直接乘成「金额」,变量名还叫 quarter。可读性差(进函数时是 3 枚,出函数时是 0.75 美元),但省了两个变量。
主循环 :
1 2 3 4 5 6 7 8 9 10 11 12 def coffee_machine(): on = True while on: choice = input("What would you like? ...") if choice == 'report': report() coffee_machine() # ← 递归! elif choice == 'off': print("Turning off.") on = False elif check_resources(choice): ...
report 分支里调了 coffee_machine() :本来只想「打印报表后继续循环」,结果又开了一层新循环 。看一次报表就多一层栈,而且外层循环回来还会再问一次「要什么」——打字时会出现连续两个提示 。正确写法是 continue。
没有 else 兜底 :输入 "tea" → check_resources("tea") → MENU["tea"] → KeyError 直接崩 。
付款判断把 process_coins 调了三遍 :
1 2 3 4 5 6 if process_coins(quarters, dimes, nickles, pennies) == MENU[choice]['cost']: ... elif process_coins(quarters, dimes, nickles, pennies) > MENU[choice]['cost']: ... else: print(f"Not enough money, ${(process_coins(...))} refunded.")
算三次结果一样(纯函数),但明显该先存一个变量 paid = process_coins(...)。
「正好等于」和「大于」两段代码几乎完全一样 (都是扣料、加钱、出货),只有「找零」那行不同。合成一段更清楚:
1 2 3 4 5 6 7 8 9 paid = process_coins(q, d, n, p) if paid < cost: print(f"Not enough money, ${paid} refunded.") else: deduct_resources(choice) money['value'] += cost if paid > cost: print(f"Here is ${round(paid - cost, 2)} in change.") print(f"Here is your {choice} ☕")
这份代码的问题
report 用递归代替 continue ,看几次报表就叠几层。
非法饮品名直接 KeyError 。
process_coins 重复调用三次 。
espresso 的 milk 键缺失靠特判绕过 ,应该用 .get('milk', 0)。
money 用单键字典 ,是为了绕 global,代价是可读性。
round(change, 2) 只处理显示 ,浮点误差仍在(0.1+0.2 那类),真实收款要用 Decimal 或全部换算成「分」的整数。
README.md(6 行)
标题 Day 15 - Local Development Environment Setup & the Coffee Machine,知识点:Installing Python Locally、Downloading PyCharm、PyCharm's Features、Running Code。
这一天开始从 Replit 转到本地 IDE ,所以代码里已经没有 from replit import clear 了。README 短,是因为当天大量时间花在装环境上。
Coffee Machine Program Requirements.pdf
课程发的需求文档(69KB)。程序里的 MENU、初始库存 300/200/100、四种硬币面值,都来自这份文档 。想核对数值就打开它——这也是「不编」的做法:数字有出处。
关键对照:Day 15 vs Day 16
同一天的需求,Day 15 用过程式 (一个文件、四个函数、全局字典),Day 16 用面向对象 (四个类、四个文件)。先写脏的、再用类重构 ——这个顺序比直接上类更容易理解「类到底解决了什么问题」。