0

I'm writing a program that asks simple calculations from the user. The idea is to pass the calculation operator as an argument, it can be addition, subtraction, multiplication or division. I'd like to something like the following work:

def ask(a,b,op):
  x = input( a, str(op), b, "=") 
  return ( x == op(a,b) )


#MAIN:
   ask(4, 6, operator.add )

The idea is that this would produce prompt: 4+6=

The problem is of course that str doesn't work that way, and I can't find anything similar in the python documentation or google (it's hard to google, since the word "operator" is so common).

  • Does this answer your question? [How to pass an operator to a python function?](https://stackoverflow.com/questions/18591778/how-to-pass-an-operator-to-a-python-function) – Gino Mempin Jan 21 '21 at 12:41
  • It does, Gino, but I was hoping there would be a simpler way to do it. – user3010768 Jan 21 '21 at 16:15
  • I think you would have to define what "simpler" means. It is subjective, because to me the solution to [map str(op) to operator](https://stackoverflow.com/a/18591880/2745495) looks "simple" enough (clear/readable, no external libs). – Gino Mempin Jan 22 '21 at 02:43

1 Answers1

0

If you have a limited amount of symbols, it's probably best to make a dictionary assigning them to each other. Like {operator.add: '+', ...}.

Afaik there's now way to find a symbol from an operator function. Best I could do was

import operator

def ask(a, b, op):
    x = input(f"{op.__name__} {a} and {b} =") 
    return (int(x) == op(a,b))

print(ask(4, 2, operator.add))

Which will give you the name (not symbol) of the operator

Lukas Schmid
  • 1,895
  • 1
  • 6
  • 18
  • That solves the problem although I was hoping there being more simple solution. It's of course useful to know there isn't one, so many thanks! I'm a newbie and thus can't upvote your answet though. – user3010768 Jan 21 '21 at 16:18