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

如何为Python计算器添加基于计算结果的连续运算功能?

带连续运算功能的Python计算器

以下是添加了连续运算功能的计算器代码,支持在输出结果后选择是否用该结果继续进行运算:

def add(n1, n2):
    return n1 + n2

def sub(n1, n2):
    return n1 - n2

def mul(n1, n2):
    return(n1 * n2)

def div(n1, n2):
    return n1 / n2 

def pow(n1, n2):
    return n1 ** n2

operations = {
    "+ = Add": add,
    "- = Subtract": sub,
    "* = Muliply": mul,
    "/ = Division": div,
    "** = Power": pow
}

try:
    # 初始化第一个数字作为当前结果
    current_result = float(input("Enter first number: "))
    
    while True:
        # 展示所有可用运算符
        for sym in operations:
            print(sym)
        
        # 获取用户选择的运算符
        operator = input("Pick an operator from the line above: ")
        
        # 校验运算符有效性
        if operator not in ['+', '-', '*', '/', '**']:
            print("Enter a valid operator.")
            continue
        
        # 获取第二个运算数字
        num2 = float(input("Enter second number: "))
        
        # 执行对应运算并更新当前结果
        if operator == "+":
            current_result = add(current_result, num2)
        elif operator == "-":
            current_result = sub(current_result, num2)
        elif operator == "*":
            current_result = mul(current_result, num2)
        elif operator == "/":
            current_result = div(current_result, num2)
        elif operator == "**":
            current_result = pow(current_result, num2)
        
        # 输出当前计算结果
        print(f"Result: {current_result}")
        
        # 询问用户是否继续运算
        continue_choice = input("是否使用该结果继续运算?输入'y'确认,'n'退出: ").lower()
        if continue_choice != 'y':
            print("退出计算器。")
            break
except ValueError:
    print("Enter valid inputs.")

关键修改说明

  • 引入current_result变量存储每次运算的结果,作为下一次连续运算的第一个操作数
  • 使用while True循环实现连续运算逻辑,直到用户选择退出
  • 增加运算符有效性校验,避免无效输入导致程序异常
  • 每次运算结束后询问用户是否继续,根据输入决定是否终止循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:00:57