以运算符为参数起作用

时间:2019-02-26 03:50:56

标签: python function operators

我只是为了好玩才开始编码,我正在尝试构建一个使用userinput的计算器。 2个数字和一个运算符。我对编码真的很陌生,目前仅限于非常简单地使用if语句和while / for循环,我才开始研究函数。我一直在尝试将这段代码放入函数中,但是我找不到使用字符串“ operator”作为函数中实际运算符的解决方案。

必须有一种方法可以缩短所有这些时间。

if used_op == "+":
    print(">  " + str(number_1) + " + " + str(number_2) + " = " + str(number_1 + number_2) + "  <")
elif used_op == "-":
    print(">  " + str(number_1) + " - " + str(number_2) + " = " + str(number_1 - number_2) + "  <")
elif used_op == "*":
    print(">  " + str(number_1) + " * " + str(number_2) + " = " + str(number_1 * number_2) + "  <")
elif used_op == "/":
    print(">  " + str(number_1) + " / " + str(number_2) + " = " + str(number_1 / number_2) + "  <")
elif used_op == "%":
    print(">  " + str(number_1) + " % " + str(number_2) + " = " + str(number_1 % number_2) + "  <")
elif used_op == "**":
    print(">  " + str(number_1) + " ** " + str(number_2) + " = " + str(number_1 ** number_2) + "  <")
elif used_op == "//":
    print(">  " + str(number_1) + " // " + str(number_2) + " = " + str(number_1 // number_2) + "  <")

我尝试过的是这样的:

def solve(op):
    print(">  " + str(number_1) + op + str(number_2) + " = " + str(
        number_1 + **op** + number_2) + "  <")

solve(used_op)

一段时间以来,我试图在互联网上找到解决方案,但到目前为止我还没有运气。

2 个答案:

答案 0 :(得分:2)

您可以使用字典和operator模块来完成所需的操作:

import operator

# this will act like a sort of case statement or switch
operations = {
    '>': operator.gt,
    '<': operator.lt,
    '=': operator.eq,
    '+': operator.add,
    '-': operator.sub,
    '/': operator.div,
    '*': operator.mul,
    '**': operator.pow,
    '//': operator.floordiv,
    ... # so on and so forth
}

def calculate(num1, num2, op):
    # operation is a function that is grabbed from the dictionary
    operation = operations.get(op)
    if not operation:
         raise KeyError("Operation %s not supported"%op)

    # Call the operation with your inputs
    num3 = operation(num1, num2)
    print('%3.2f %s %3.2f = %3.2f' % (num1, op, num2, num3))


calculate(1,2, '+')
# 1.00 + 2.00 = 3.00

答案 1 :(得分:-1)

只需 求值 ,您的数学表达式和python即可为您完成剩下的工作。

这当然可以通过内置的eval()函数来完成。

以下是一些如何使用它的示例:

>>> eval("1+1")
2

>>> A = 2
>>> eval("A * 3")
6

您要编写的函数可能看起来像这样

def solve(a, b, op):
    expression = str(a) + op + str(b)
    print("> " + expression + "=" + str(eval(expression)))

solve(1, 2, "+")   # > 1+2=3
solve(10, 10, "*") # > 10*10=100
solve(4, 2, "/")   # > 4/2=2.0
solve(5, 10, "-")  # > 5-10=-5