Python实战案例详解:基于计算器项目的扩展应用
以计算器案例,复习之前的知识
·
案例1:增强版计算器(带异常处理)
# 计算器历史记录
history = []
def calculate(operation, a, b):
"""执行计算并记录历史"""
try:
if operation == "+":
result = a + b
record = f"{a} + {b} = {result}"
elif operation == "-":
result = a - b
record = f"{a} - {b} = {result}"
elif operation == "*":
result = a * b
record = f"{a} * {b} = {result}"
elif operation == "/":
result = a / b
record = f"{a} / {b} = {result}"
else:
raise ValueError("无效的操作符")
history.append(record)
return result
except ZeroDivisionError:
print("错误:除数不能为零")
return None
except 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("感谢使用计算器!")
break
elif 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("无效选择,请重新输入!")
关键点解析:
-
使用
try-except捕获除零错误和类型转换错误 -
通过
raise主动抛出异常处理无效操作符 -
历史记录功能使用列表存储字符串格式的记录
-
操作选择使用数字映射到运算符,提高用户体验
案例2:科学计算器(带函数默认参数)
import math
def 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")) # 触发错误
关键点解析:
-
使用字典映射字符串到数学函数,实现灵活调用
-
函数参数设置默认值,简化调用
-
结果保留指定位数小数
-
处理负数开平方等数学错误
案例3:带记忆功能的计算器(使用字典存储变量)
memory = {} # 存储变量
def evaluate(expression):
"""计算表达式"""
try:
# 替换内存变量
for var in memory:
expression = expression.replace(var, str(memory[var]))
return eval(expression) # 注意:实际项目中慎用eval
except (SyntaxError, NameError):
print("表达式错误!")
return None
while True:
print("\n=== 记忆计算器 ===")
print("1. 计算表达式")
print("2. 存储变量")
print("3. 查看变量")
print("4. 退出")
choice = input("请选择(1-4): ")
if choice == "4":
break
elif 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("无效选择!")
关键点解析:
-
使用字典存储变量名和值
-
通过字符串替换实现变量代入
-
eval()函数的使用和安全性考虑 -
字典遍历展示存储的变量
案例4:带图形界面的计算器(使用tkinter)
import tkinter as tk
from tkinter import messagebox
class CalculatorApp:
def __init__(self, master):
self.master = master
master.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 // 4
col = i % 4
btn = 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()
关键点解析:
-
使用tkinter创建图形界面
-
网格布局管理按钮
-
lambda函数处理按钮事件
-
基本的异常处理
关键知识速查表应用案例
列表切片应用:计算器历史分页显示
def show_history(page=1, page_size=5):
"""分页显示历史记录"""
start = (page-1) * page_size
end = start + page_size
current_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_size
if 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基础知识在实际项目中的应用。
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐

所有评论(0)