You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python计算器程序中使用?访问历史记录时提示“未识别操作”的问题求助

Python计算器程序中使用?访问历史记录时提示“未识别操作”的问题求助

看起来你遇到的问题根源在于两处代码逻辑的疏漏,咱们一步步梳理和修复:

问题分析

  1. 操作符判断遗漏?:你的select_op函数里,在判断有效操作符时只包含了+、-、*、/、^、%,完全没把触发历史记录的?加进去——所以输入?时会直接走到最后的else分支,输出“Unrecognized operation”。
  2. 历史记录逻辑位置错误:你把处理?的代码写在需要输入两个数字的计算操作代码块里,就算?能进入这个块,也会先执行输入数字的循环,这显然不符合查看历史的需求——查看历史根本不需要输入数字。

修复方案

我们需要调整代码结构,先处理?这类特殊操作,再处理计算类操作,同时优化文件操作的安全性:

关键修改点

  • 把?单独作为一个分支处理,不和计算类操作混在一起
  • 将历史记录相关的函数移到外部,避免嵌套函数的混乱
  • 使用with语句操作文件,确保文件自动关闭,避免资源泄漏
  • 调整select_op的判断顺序,先处理所有特殊指令(#、$、?),再处理计算操作

修改后的完整代码

from random import choice

def add(a,b):
    return a+b
  
def subtract(a,b):
    return a-b
  
def multiply(a,b):
    return a*b

def divide(a,b):
    try:
        return a/b
    except Exception as e:
        print(e)
        return None  # 返回None避免后续写入无效历史

def power(a,b):
    return a**b
  
def remainder(a,b):
    return a%b

# 拆分历史记录操作,职责更清晰
def save_history(num1, op, num2, result):
    if result is not None:  # 仅保存成功的计算记录
        with open("calc_his.txt", "a") as his_file:
            his_file.write(f"{num1} {op} {num2} = {result}\n")

def load_history():
    try:
        with open("calc_his.txt", "r") as his_file:
            print(his_file.read())
    except FileNotFoundError:
        print("暂无历史记录")
  
def select_op(choice):
    if choice == '#':
        return -1
    elif choice == '$':
        return 0
    elif choice == '?':
        # 单独处理历史记录查看,无需输入数字
        load_history()
        return 0  # 返回主循环继续接受操作
    elif choice in ('+','-','*','/','^','%'):
        # 以下为原有的输入数字与计算逻辑
        while True:
            num1s = input("Enter first number: ")
            print(num1s)
            if num1s.endswith('$'):
                return 0
            if num1s.endswith('#'):
                return -1
                
            try:
                num1 = float(num1s)
                break
            except:
                print("Not a valid number,please enter again")
                continue
    
        while True:
            num2s = input("Enter second number: ")
            print(num2s)
            if num2s.endswith('$'):
                return 0
            if num2s.endswith('#'):
                return -1
            try:  
                num2 = float(num2s)
                break
            except:
                print("Not a valid number, please enter again")
                continue
    
        result = None
        if choice == '+':
            result = add(num1, num2)
        elif choice == '-':
            result = subtract(num1, num2)
        elif choice == '*':
            result = multiply(num1, num2)
        elif choice == '/':
            result = divide(num1, num2)
        elif choice == '^':
            result = power(num1, num2)
        elif choice == '%':
            result = remainder(num1, num2)
        
        if result is not None:
            last_calculation = f"{num1} {choice} {num2} = {result}" 
            print(last_calculation)
            save_history(num1, choice, num2, result)
        else:
            print("计算失败,未保存到历史")
    else:
        print("Unrecognized operation")
      
while True:
    print("Select operation.")
    print("1.Add      : + ")
    print("2.Subtract : - ")
    print("3.Multiply : * ")
    print("4.Divide   : / ")
    print("5.Power    : ^ ")
    print("6.Remainder: % ")
    print("7.Terminate: # ")
    print("8.Reset    : $ ")
    print("9.History  : ? ")  # 修复了重复编号的问题
    
    # take input from the user
    choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
    print(choice)
    if select_op(choice) == -1:
        # program ends here
        print("Done. Terminating")
        exit()

额外优化说明

  • 用f-string替代了繁琐的字符串拼接,代码更简洁易读
  • 给divide函数增加了return None,避免除零错误时写入无效历史
  • 修复了主菜单里历史记录的重复编号问题

这样修改后,输入?就会直接触发历史记录查看,不会再提示“未识别操作”啦!

备注:内容来源于stack exchange,提问作者somerandomboi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 14:04:35