# Python 如何制作使用运算符作为输入的计算器功能

I started learning Python yesterday; this is the first calculator I've made. I noticed that the last lines of code that print the equation's result are repeated.

Can I write a function that takes the operator as input and then prints the result with just one line of code?

I imagine it would be something like this:

def result(operator):

print((str(num1)) + " " + str(operator) + " " + str(num2) + " = " + str(num1 insert operator to compute equation num2))

``````    num1 = float(input("Enter first number: "))

op = None
while op not in ("-", "+", "*", "/"):
op = input("Enter operator (-, +, *, /):  ")

num2 = float(input("Enter second number: "))

if op == "-":
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 - num2))
elif op == "+":
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 + num2))
elif op == "*":
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 * num2))
elif op == "/":
print((str(num1)) + " " + str(op) + " " + str(num2) + " = " + str(num1 / num2))
``````

## 推荐答案

You might try using a dictionary to map strings (operators) to function objects:

``````from operator import add, sub, mul, floordiv

operations = {
"-": sub,
"*": mul,
"/": floordiv
}

a = float(input("Enter first number: "))

while (op := input("Enter operator: ")) not in operations: pass

# 'operation' is one of the four functions - the one 'op' mapped to.
operation = operations[op]

b = float(input("Enter second number: "))

# perform whatever operation 'op' mapped to.
result = operation(a, b)

print(f"{a} {op} {b} = {result}")
``````

In this case, `add`, `sub`, `mul` and `floordiv` are the function objects, each of which take two parameters, and return a number.