You better do not specify the operators as text. Simply use lambda expressions, or the operator
module:
import operator
import random
operators = [operator.add,operator.sub,operator.mul,operator.floordiv]
op = random.choice(operators)
You can then call the op
by calling it with two arguments, like:
result = op(2,3)
For example:
>>> import operator
>>> import random
>>>
>>> operators = [operator.add,operator.sub,operator.mul,operator.floordiv]
>>> op = random.choice(operators)
>>> op
<built-in function sub>
>>> op(4,2)
2
So as you can see, the random
picked the sub
operator, so it subtracted 2
from 4
.
In case you want to define an function that is not supported by operator
, etc. you can use a lambda-expression, like:
operators = [operator.add,lambda x,y:x+2*y]
So here you specified a function that takes the parameters x
and y
and calculates x+2*y
(of course you can define an arbitrary expression yourself).