Python编程题调试求助:myprogramminglab烘焙店库存程序输出错误
问题排查与代码修正:MyProgrammingLab 松饼/纸杯蛋糕库存程序输出错误
问题根源
- 程序开头的
print('Initial Stock: ...')属于多余输出,测试用例未要求打印初始库存,这部分内容导致_stdout包含额外信息,与预期结果不匹配。 - 代码中
input()函数的提示文本(What do you want? (muffin/cupcake or 0 to quit):)会被计入_stdout,但测试用例仅期望程序处理输入后的响应内容(如购买成功提示、缺货提示或最终库存),提示语的存在直接导致输出错误。 - 原代码的缺货提示多了感叹号(
Out of stock!),与题目要求的Out of stock格式不符。
修正后的代码
# 初始化库存变量 muffins = 10 cupcakes = 5 choice = "" while choice != "0": # 直接读取输入,不输出交互提示 choice = input().strip() if choice.lower() == "muffin": if muffins > 0: muffins -= 1 print(f'You bought a muffin. Number of muffins left: {muffins}') else: print('Out of stock') elif choice.lower() == "cupcake": if cupcakes > 0: cupcakes -= 1 print(f'You bought a cupcake. Number of cupcakes left: {cupcakes}') else: print('Out of stock') elif choice == "0": print(f'muffins: {muffins} cupcakes: {cupcakes}')
关键修正说明
- 移除初始库存打印:完全删除初始库存的输出语句,确保_stdout仅包含测试用例要求的内容。
- 删除输入提示语:使用
input().strip()直接读取标准输入,避免提示文本混入输出结果。 - 统一输出格式:将缺货提示修正为题目要求的
Out of stock,同时用f-string简化输出格式,保证与题目示例完全匹配。
内容的提问来源于stack exchange,提问作者Paul Condon Jr
相关产品推荐
相关产品推荐

