我刚刚开始编写代码是为了好玩,我正在尝试构建一个使用用户输入的计算器。 2 个号码和 1 个运算符。我对编码真的很陌生,目前仅限于 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)
我尝试在互联网上找到解决方案一段时间,但到目前为止我没有运气。
最佳答案
您可以使用字典和 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
关于python - 以运算符作为参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54878202/