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

如何不使用if else语句编写Python计算器及修复现有代码问题

问题修复方案

你现有代码存在多个核心错误,以下是逐点修正说明和可运行代码:

1. 存在的问题

  • 函数字典operations_and_functions中存储的是函数名字符串,而非可调用的函数对象,无法直接执行
  • 自定义pow函数中使用的^是Python按位异或运算符,不是幂运算,幂运算需用**
  • 函数调用逻辑重复:你已经在calculation = operations_and_functions[operation](num1,num2)中执行了一次函数得到计算结果,后续又把结果作为函数二次调用,逻辑完全错误
  • add函数的return语句缺少缩进,会直接报语法错误
  • input本身返回的就是字符串,不需要额外用str()转换

2. 修复后完整代码

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_and_functions= {
    "+": add,
    "-": sub,
    "*": mul,
    "/": div,
    "^": pow,
}

num1 = int(input("What is your first number=> "))
num2 = int(input("What is your second number=> "))
# 打印支持的运算符
print("支持的运算符如下:")
for op in operations_and_functions:
    print(op)
operation = input("What operation do you want to do=> ")

# 直接取到函数对象后调用一次即可
calc_func = operations_and_functions[operation]
answer = calc_func(num1, num2)
print(f"{num1} {operation} {num2} is equal to {answer}")

3. 核心逻辑说明

你要的无if/else调用逻辑是通过字典映射实现的:将运算符作为key,对应的计算函数作为value存储,拿到用户输入的运算符后直接从字典中取出对应函数,传入参数执行即可,无需分支判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:45:02