【AI大模型--python基础3】
·
成果编写–编写终端计算器
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
import sys
class CommandLineCalculator:
def __init__(self):
self.memory = 0
self.history = []
def evaluate(self, expression):
"""安全地计算数学表达式"""
# 允许的字符和函数
allowed_names = {
'abs': abs, 'round': round, 'min': min, 'max': max,
'sin': math.sin, 'cos': math.cos, 'tan': math.tan,
'asin': math.asin, 'acos': math.acos, 'atan': math.atan,
'sinh': math.sinh, 'cosh': math.cosh, 'tanh': math.tanh,
'sqrt': math.sqrt, 'log': math.log, 'log10': math.log10,
'exp': math.exp, 'pi': math.pi, 'e': math.e, 'tau': math.tau
}
try:
# 使用eval但限制命名空间
code = compile(expression, "<string>", "eval")
for name in code.co_names:
if name not in allowed_names and not name.startswith('_'):
raise NameError(f"不允许使用名称: {name}")
result = eval(expression, {"__builtins__": {}}, allowed_names)
return result
except Exception as e:
raise ValueError(f"表达式错误: {e}")
def run(self):
"""运行计算器主循环"""
print("=" * 50)
print("命令行计算器已启动")
print("支持运算: +, -, *, /, **, %, //")
print("支持函数: sin, cos, tan, sqrt, log, exp, abs, round")
print("可用常量: pi, e, tau")
print("特殊命令: help, clear, mem, history, exit")
print("=" * 50)
while True:
try:
# 获取用户输入
user_input = input("\n计算: ").strip()
if not user_input:
continue
# 处理特殊命令
if user_input.lower() == 'exit':
print("感谢使用计算器,再见!")
break
elif user_input.lower() == 'help':
self.show_help()
continue
elif user_input.lower() == 'clear':
self.clear_screen()
continue
elif user_input.lower() == 'mem':
print(f"内存值: {self.memory}")
continue
elif user_input.lower() == 'history':
self.show_history()
continue
elif user_input.startswith('mem='):
try:
self.memory = float(user_input[4:])
print(f"内存已设置为: {self.memory}")
except ValueError:
print("错误: 无效的内存值")
continue
# 计算结果
result = self.evaluate(user_input)
# 显示结果
print(f"结果: {result}")
# 保存到历史记录
self.history.append((user_input, result))
# 自动保存到内存(可选)
# self.memory = result
except KeyboardInterrupt:
print("\n\n检测到中断,退出计算器...")
break
except Exception as e:
print(f"错误: {e}")
def show_help(self):
"""显示帮助信息"""
print("\n" + "=" * 50)
print("帮助信息:")
print("-" * 50)
print("基本运算:")
print(" 加法: 2 + 3")
print(" 减法: 5 - 2")
print(" 乘法: 4 * 6")
print(" 除法: 10 / 3")
print(" 整除: 10 // 3")
print(" 取模: 10 % 3")
print(" 幂运算: 2 ** 3")
print("\n函数运算:")
print(" 平方根: sqrt(16)")
print(" 三角函数: sin(pi/2), cos(0), tan(1)")
print(" 对数: log(100), log10(100)")
print(" 指数: exp(2)")
print(" 绝对值: abs(-5)")
print(" 四舍五入: round(3.14159, 2)")
print(" 最大值: max(1, 2, 3)")
print(" 最小值: min(1, 2, 3)")
print("\n特殊命令:")
print(" mem - 查看内存值")
print(" mem=数值 - 设置内存值")
print(" history - 查看计算历史")
print(" clear - 清屏")
print(" help - 显示此帮助")
print(" exit - 退出程序")
print("=" * 50)
def clear_screen(self):
"""清屏功能"""
import os
os.system('cls' if os.name == 'nt' else 'clear')
print("屏幕已清空")
def show_history(self):
"""显示历史记录"""
if not self.history:
print("暂无历史记录")
else:
print("\n计算历史:")
print("-" * 30)
for i, (expr, result) in enumerate(self.history[-10:], 1):
print(f"{i}. {expr} = {result}")
print("-" * 30)
def main():
"""主函数"""
calculator = CommandLineCalculator()
calculator.run()
if __name__ == "__main__":
main()
计算器注释说明
命令行计算器 (CommandLineCalculator) 详解
概述
这是一个功能丰富的命令行科学计算器,使用 Python 实现,支持基础运算、三角函数、对数运算、内存管理和历史记录等功能。
类结构
CommandLineCalculator 类
主计算器类,提供所有计算功能。
属性
| 属性 | 类型 | 说明 |
|---|---|---|
self.memory |
float | 内存寄存器,存储临时数值 |
self.history |
list | 计算历史记录列表,存储 (表达式, 结果) 元组 |
方法详解
1. __init__() - 初始化
def __init__(self):
self.memory = 0
self.history = []
初始化计算器,内存清零,历史记录为空列表。
2. evaluate(expression) - 安全表达式计算
参数: expression (str) - 数学表达式字符串
返回值: 计算结果
功能说明:
- 使用白名单机制限制可使用的函数和常量
- 编译表达式检查所有引用的名称
- 使用受限的 eval 执行计算
允许的名称表:
| 类别 | 名称 |
|---|---|
| 数学函数 | abs, round, min, max |
| 三角函数 | sin, cos, tan, asin, acos, atan |
| 双曲函数 | sinh, cosh, tanh |
| 其他函数 | sqrt, log, log10, exp |
| 常量 | pi, e, tau |
安全机制:
for name in code.co_names:
if name not in allowed_names and not name.startswith('_'):
raise NameError(f"不允许使用名称: {name}")
- 检查所有变量名是否在白名单中
- 禁止访问私有属性
- 通过
{"__builtins__": {}}禁用内建函数
异常处理: 捕获所有异常并抛出 ValueError
3. run() - 主循环
程序的主入口,运行交互式计算循环。
流程图:
开始
↓
显示欢迎信息
↓
while True:
├─ 获取用户输入
├─ 空输入 → 继续
├─ 处理特殊命令:
│ ├─ exit → 退出
│ ├─ help → 显示帮助
│ ├─ clear → 清屏
│ ├─ mem → 显示内存
│ ├─ history → 显示历史
│ └─ mem=数值 → 设置内存
├─ 计算表达式
├─ 显示结果
├─ 保存到历史
└─ 异常处理
↓
结束
支持的特殊命令:
| 命令 | 功能 |
|---|---|
help |
显示帮助信息 |
clear |
清空屏幕 |
mem |
查看当前内存值 |
mem=数值 |
设置内存值 |
history |
查看最近10条历史 |
exit |
退出程序 |
4. show_help() - 帮助信息
显示所有支持的功能和使用方法。
显示内容:
- 基本运算:+, -, *, /, //, %, **
- 函数运算:sqrt, sin, cos, tan, log, log10, exp, abs, round, min, max
- 常量:pi, e, tau
- 特殊命令:mem, history, clear, help, exit
5. clear_screen() - 清屏
def clear_screen(self):
import os
os.system('cls' if os.name == 'nt' else 'clear')
跨平台清屏实现:
- Windows (nt): 使用
cls命令 - Unix/Linux/Mac: 使用
clear命令
6. show_history() - 历史记录
显示计算历史,最多显示最近10条记录。
输出格式:
计算历史:
------------------------------
1. 2 + 3 = 5
2. sqrt(16) = 4
...
------------------------------
使用示例
基本运算
计算: 2 + 3
结果: 5
计算: 10 / 3
结果: 3.3333333333333335
计算: 2 ** 8
结果: 256
科学计算
计算: sqrt(16)
结果: 4.0
计算: sin(pi/2)
结果: 1.0
计算: log(exp(1))
结果: 1.0
计算: max(1, 5, 3, 9, 2)
结果: 9
内存操作
计算: mem=100
内存已设置为: 100.0
计算: mem
内存值: 100.0
安全设计
- 沙箱执行: 通过限制
__builtins__和白名单实现 - 名称检查: 编译时验证所有变量名
- 异常隔离: 捕获所有计算异常,不影响主循环
- 禁止私有访问: 阻止访问
_开头的属性
扩展建议
- 添加角度/弧度切换功能
- 支持变量赋值 (如
x = 5) - 添加进制转换功能
- 支持表达式别名/宏
- 添加单位转换
- 支持结果导出为文件
运行方式
python codeCalc.py
文档生成时间: 2026-05-06
更多推荐




所有评论(0)