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

Python基于列表实现带历史记录计算器的代码问题修复

问题描述
  • 基于列表实现带历史查询功能的Python计算器时,触发?历史查询操作始终返回提示No past calculations to show,无法正常展示已执行的计算记录
  • 现有代码已实现加、减、乘、除、幂、取余6个基础运算函数,支持#终止程序、$重置程序的逻辑,需要完成两项修改:
    • 声明统一列表存储过往运算记录,每次计算完成后将操作符、两个操作数、运算结果拼接为单条字符串存入列表
    • 实现独立的history()函数处理?历史查询操作,按运算执行顺序输出全部存储的历史记录,无历史记录时输出指定提示No past calculations to show
原代码问题根因
  • 存储逻辑错误:为每个运算符单独定义空列表存储记录,且列表定义在select_op()函数内部,每次调用函数都会将所有存储列表重新初始化为空,之前保存的运算记录会直接丢失
  • 分支判断错误:将?归入需要输入两个操作数的运算分支,选中历史查询后会先要求输入两个数字,根本无法走到后续的历史查询判断逻辑
  • 未按要求实现独立的历史查询处理函数,逻辑耦合在运算分支中
  • 菜单选项序号重复,重置和历史查询都标记为8
修复后完整代码
# 全局统一历史记录存储列表
history_records = []

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)

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

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

# 独立历史查询处理函数
def history():
    if len(history_records) == 0:
        print("No past calculations to show")
    else:
        print("\n".join(history_records))

def select_op(choice): 
    if choice == '#':
        print("Done. Terminating")
        exit()
    elif choice == '$':
        # 重置时清空所有历史记录
        history_records.clear()
        return main()
    elif choice == '?':
        # 直接调用历史查询,不进入数字输入流程
        history()
        return
    elif choice in ('+','-','*','/','^','%'):
        while True:
            num1s = str(input("Enter first number: "))
            print(num1s)
            if num1s.endswith('$'):
                history_records.clear()
                return main()
            if num1s.endswith('#'):
                print("Done. Terminating")
                exit()   
            try:
                num1 = float(num1s)
                break
            except:
                print("Not a valid number,please enter again")
                continue
        
        while True:
            num2s = str(input("Enter second number: "))
            print(num2s)
            if num2s.endswith('$'):
                history_records.clear()
                return main()
            if num2s.endswith('#'):
                print("Done. Terminating")
                exit()
            try:  
                num2 = float(num2s)
                break
            except:
                print("Not a valid number,please enter again")
                continue

        if choice == '+':
            result = add(num1, num2)
            msg = f"{num1} {choice} {num2} = {result}"
            print(msg)
            history_records.append(msg)
        elif choice == '-':
            result = subtract(num1, num2)
            msg = f"{num1} {choice} {num2} = {result}"
            print(msg)
            history_records.append(msg)
        elif choice == '*':
            result = multiply(num1, num2)
            msg = f"{num1} {choice} {num2} = {result}"
            print(msg)
            history_records.append(msg)
        elif choice == '/':
            result = divide(num1, num2)
            msg = f"{num1} {choice} {num2} = {result}"
            print(msg)
            history_records.append(msg)
        elif choice == '^':
            result = power(num1, num2)
            msg = f"{num1} {choice} {num2} = {result}"
            print(msg)
            history_records.append(msg)
        elif choice == '%':
            result = remainder(num1, num2)
            msg = f"{num1} {choice} {num2} = {result}"
            print(msg)
            history_records.append(msg)
    else:
        print("Unrecognized operation")
        return main()

def main():   
    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  : ? ")

        choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
        print(choice)
        select_op(choice)

main()
关键修改说明
  • 全局声明统一列表history_records存储所有运算记录,不会因为函数重复调用被重置,所有运算完成后将格式化好的计算字符串统一追加到该列表
  • 实现独立的history()函数,专门处理历史查询逻辑,无记录时输出要求的提示文本,有记录时按存入顺序逐行打印
  • 调整分支判断顺序,将?历史查询的判断提前,选中该操作时直接调用查询函数,不会错误触发数字输入流程
  • 补全重置逻辑,触发$重置操作时清空历史记录列表,符合重置功能的预期
  • 修复菜单序号重复问题,将历史查询的菜单序号改为9
  • 删除原代码中为每个运算符单独定义的6个零散存储列表,简化存储逻辑

内容的提问来源于stack exchange,提问作者Nima

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 06:01:00