当前位置: 首页 > ops >正文

Python实战案例详解:基于计算器项目的扩展应用

案例1:增强版计算器(带异常处理)

# 计算器历史记录
history = []def calculate(operation, a, b):"""执行计算并记录历史"""try:if operation == "+":result = a + brecord = f"{a} + {b} = {result}"elif operation == "-":result = a - brecord = f"{a} - {b} = {result}"elif operation == "*":result = a * brecord = f"{a} * {b} = {result}"elif operation == "/":result = a / brecord = f"{a} / {b} = {result}"else:raise ValueError("无效的操作符")history.append(record)return resultexcept ZeroDivisionError:print("错误:除数不能为零")return Noneexcept Exception as e:print(f"发生错误:{e}")return None# 主程序
while True:print("\n=== 增强版计算器 ===")print("1. 加法 (+)")print("2. 减法 (-)")print("3. 乘法 (*)")print("4. 除法 (/)")print("5. 查看历史")print("6. 退出")choice = input("请选择操作(1-6): ")if choice == "6":print("感谢使用计算器!")breakelif choice == "5":print("\n=== 计算历史 ===")print("\n".join(history) if history else "暂无历史记录")elif choice in ("1", "2", "3", "4"):operations = ["+", "-", "*", "/"]operation = operations[int(choice)-1]try:x = float(input("输入第一个数: "))y = float(input("输入第二个数: "))result = calculate(operation, x, y)if result is not None:print(f"结果: {result}")except ValueError:print("错误:请输入有效数字!")else:print("无效选择,请重新输入!")

关键点解析

  1. 使用try-except捕获除零错误和类型转换错误

  2. 通过raise主动抛出异常处理无效操作符

  3. 历史记录功能使用列表存储字符串格式的记录

  4. 操作选择使用数字映射到运算符,提高用户体验

案例2:科学计算器(带函数默认参数)

import mathdef sci_calc(value, func="sqrt", round_to=2):"""科学计算函数:param value: 要计算的值:param func: 计算函数,支持'sqrt','sin','cos','log':param round_to: 结果保留小数位数:return: 计算结果"""operations = {"sqrt": math.sqrt,"sin": math.sin,"cos": math.cos,"log": math.log}if func not in operations:raise ValueError(f"不支持的函数:{func}")try:result = operations[func](value)return round(result, round_to)except ValueError as e:print(f"计算错误:{e}")return None# 使用示例
print(sci_calc(16))  # 默认计算平方根,输出: 4.0
print(sci_calc(3.14, "sin", 4))  # 计算sin(3.14)保留4位小数
print(sci_calc(-1, "sqrt"))  # 触发错误

关键点解析

  1. 使用字典映射字符串到数学函数,实现灵活调用

  2. 函数参数设置默认值,简化调用

  3. 结果保留指定位数小数

  4. 处理负数开平方等数学错误

案例3:带记忆功能的计算器(使用字典存储变量)

memory = {}  # 存储变量def evaluate(expression):"""计算表达式"""try:# 替换内存变量for var in memory:expression = expression.replace(var, str(memory[var]))return eval(expression)  # 注意:实际项目中慎用evalexcept (SyntaxError, NameError):print("表达式错误!")return Nonewhile True:print("\n=== 记忆计算器 ===")print("1. 计算表达式")print("2. 存储变量")print("3. 查看变量")print("4. 退出")choice = input("请选择(1-4): ")if choice == "4":breakelif choice == "1":expr = input("输入表达式(如3+5*2): ")result = evaluate(expr)if result is not None:print(f"结果: {result}")elif choice == "2":var_name = input("变量名: ")var_value = input("变量值: ")try:memory[var_name] = float(var_value)print(f"{var_name} = {memory[var_name]}")except ValueError:print("变量值必须是数字!")elif choice == "3":print("\n=== 存储的变量 ===")for name, value in memory.items():  # 字典遍历print(f"{name}: {value}")else:print("无效选择!")

关键点解析

  1. 使用字典存储变量名和值

  2. 通过字符串替换实现变量代入

  3. eval()函数的使用和安全性考虑

  4. 字典遍历展示存储的变量

案例4:带图形界面的计算器(使用tkinter)

import tkinter as tk
from tkinter import messageboxclass CalculatorApp:def __init__(self, master):self.master = mastermaster.title("GUI计算器")# 显示框self.display = tk.Entry(master, width=25, font=('Arial', 16))self.display.grid(row=0, column=0, columnspan=4, pady=10)# 按钮布局buttons = ['7', '8', '9', '/','4', '5', '6', '*','1', '2', '3', '-','0', 'C', '=', '+']# 创建按钮for i, text in enumerate(buttons):row = 1 + i // 4col = i % 4btn = tk.Button(master, text=text, width=5, height=2,command=lambda t=text: self.on_button_click(t))btn.grid(row=row, column=col, padx=5, pady=5)def on_button_click(self, char):"""处理按钮点击事件"""if char == 'C':self.display.delete(0, tk.END)elif char == '=':try:expression = self.display.get()result = eval(expression)  # 实际项目中应对表达式做安全检查self.display.delete(0, tk.END)self.display.insert(0, str(result))except Exception:messagebox.showerror("错误", "无效表达式")else:self.display.insert(tk.END, char)# 创建主窗口
root = tk.Tk()
app = CalculatorApp(root)
root.mainloop()

关键点解析

  1. 使用tkinter创建图形界面

  2. 网格布局管理按钮

  3. lambda函数处理按钮事件

  4. 基本的异常处理

关键知识速查表应用案例

列表切片应用:计算器历史分页显示

def show_history(page=1, page_size=5):"""分页显示历史记录"""start = (page-1) * page_sizeend = start + page_sizecurrent_page = history[start:end]  # 列表切片print(f"\n=== 历史记录(第{page}页) ===")print("\n".join(current_page) if current_page else "无记录")total_pages = (len(history) + page_size - 1) // page_sizeif total_pages > 1:print(f"\n页码: {page}/{total_pages}")# 在计算器主循环中添加:
# elif choice == "4":  # 分页查看历史
#     page = int(input("输入页码: "))
#     show_history(page)

函数默认参数应用:高级计算选项

def advanced_calc(x, y, operation="+", precision=2, verbose=False):"""高级计算函数"""ops = {"+": x + y,"-": x - y,"*": x * y,"/": x / y if y != 0 else float('nan')}result = round(ops.get(operation, float('nan')), precision)if verbose:print(f"{x} {operation} {y} = {result}")return result# 使用示例
advanced_calc(3.1415, 2.7182, "*", 4)  # 指定精度
advanced_calc(10, 3, verbose=True)     # 使用默认加法和精度,但打印过程

异常处理应用:安全的计算器输入

def get_number_input(prompt):"""安全的数字输入函数"""while True:try:return float(input(prompt))except ValueError:print("输入错误,请输入有效数字!")# 在主程序中使用
# x = get_number_input("第一个数: ")
# y = get_number_input("第二个数: ")

通过这些案例,我们可以看到Python基础知识在实际项目中的应用。

http://www.xdnf.cn/news/13417.html

相关文章:

  • 前端框架vue3的变化之处
  • API:解锁数字化协作的钥匙及开放实现路径深度剖析
  • HakcMyVM-Blackhat
  • Ubuntu 24.04 上安装与 Docker 部署 Sentinel
  • UE5 学习系列(六)导入资产包
  • BW非法字符处理
  • 智能空气流向控制系统SKLX的优化与实践
  • Hi3519DV500开发板适配新sensor的详细流程(最新版)
  • 96页PPT华为销售战略规划市场洞察品牌策略
  • Squid 代理服务器实战:解决动态 IP 访问第三方接口的生产级方案
  • 多系统合路器(POI)详解
  • 【数据结构】 优先级队列 —— 堆
  • 波形合成之C语言实现
  • NuGet 从入门到精进全解析
  • Intel Boot Guard
  • 系统集成自动化流程编排实现条件分支高级篇(二)
  • 实战使用docker compose 搭建 Redis 主从复制集群
  • 依存句法分析
  • Cockpit:一个开源的 Linux 系统管理工具
  • 蚁群算法(Ant Colony Optimization)原理与应用解析
  • (功能测试Charles)如何抓取手机http的报文
  • 2025神经网络动力学理论、优化算法及应用专题研讨会 ( NOTAA 2025)
  • 裸金属服务器+可信计算:构建自主可控的数据安全新底座
  • 【无标题】NP完全问题的拓扑对偶统一解法 ——四色问题到P=NP的普适框架
  • 篇章四 论坛系统——业务开发——前期准备——公共组件
  • 数据库连接池——关键技术点介绍
  • 亚马逊 API 接口开发:解锁商品详情页实时数据(接入流程解析)
  • Django中的ORM的使用步骤----以MySQL为例
  • 湖北理元理律师事务所债务优化实践:法律框架下的生活重建方案
  • 一台电脑最多能接多少个硬盘