本文教你编写一个结构清晰、错误处理完善的python四则运算计算器,解决用户输入无效选项时仍强制要求输入数字的问题,并通过条件校验前置、函数封装和可扩展设计提升代码质量。
本文教你编写一个结构清晰、错误处理完善的python四则运算计算器,解决用户输入无效选项时仍强制要求输入数字的问题,并通过条件校验前置、函数封装和可扩展设计提升代码质量。
一个看似简单的四则运算程序,常因逻辑顺序不当导致体验缺陷——例如用户输入 5(非法选项)后,程序仍继续执行 x = int(input("enter 1st numer :")),造成冗余输入与误导。根本原因在于:所有输入操作(包括数字)都放在了选项校验之后,违背了“先验证、再执行”的基本控制流原则。
以下是优化后的完整实现,采用清晰分层结构:
def show_menu():
print("[1] ADD")
print("[2] Subtract")
print("[3] Multiply")
print("[4] Divide")
print("[0] Exit")
def get_numbers():
try:
x = float(input("Enter 1st number: "))
y = float(input("Enter 2nd number: "))
return x, y
except ValueError:
print("❌ Error: Please enter valid numbers.")
return None, None
def main():
operations = {
1: ("addition", lambda a, b: a + b),
2: ("subtraction", lambda a, b: a - b),
3: ("multiplication", lambda a, b: a * b),
4: ("division", lambda a, b: a / b if b != 0 else None)
}
while True:
show_menu()
try:
choice = int(input("Enter your choice: "))
if choice == 0:
print("? Goodbye!")
break
elif choice not in operations:
print("⚠️ Invalid choice. Please select 1–4 or 0 to exit.")
continue # 跳过后续逻辑,重新显示菜单
# ✅ 此时才安全获取数字
x, y = get_numbers()
if x is None or y is None:
continue
# 执行运算
op_name, func = operations[choice]
result = func(x, y)
if choice == 4 and y == 0:
print("❌ Division by zero is not allowed.")
else:
print(f"✅ {op_name} of {x} and {y} is {result}")
except ValueError:
print("⚠️ Invalid input: Please enter an integer for choice.")
except KeyboardInterrupt:
print("\n\n? Program interrupted. Goodbye!")
break
if __name__ == "__main__":
main()关键改进说明:
- 前置校验:choice 输入后立即判断是否在有效范围内(1–4 或 0),非法则 continue,绝不进入数字输入环节;
- 异常防护:对 int()/float() 转换加 try-except,避免程序崩溃;
- 零除保护:除法单独检查 y == 0,并给出明确提示;
- 可扩展性设计:使用字典 operations 映射选项→运算名→计算函数,新增功能只需追加字典项;
- 用户体验增强:支持重复尝试、退出选项(0)、中断响应(Ctrl+C);
- 语义清晰:移除无意义赋值(如 a = print(...)),直接调用 print()。
? 小贴士:实际项目中,还可进一步封装为类、支持浮点数/整数自动识别、添加历史记录或命令行参数支持。但核心原则始终不变——输入验证永远走在业务逻辑之前。
立即学习“Python免费学习笔记(深入)”;
通过以上重构,你的计算器不再是“能跑就行”的脚本,而是一个具备鲁棒性、可维护性和专业感的入门级Python应用。


















