Skip to content
Advertisement

How to make a calculator function that uses the operator as an input?

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))

JavaScript

Advertisement

Answer

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

JavaScript

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement