3

Say I have a list with mathematical operators in it, like this

operators = ['+','-','*','/']

And I am taking a random operator from here, like this

op = random.choice(operators)

If I take two numbers, say 4 and 2, how can I get Python to do the mathematical operation (under the name 'op') with the numbers?

0

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I have tried using operator.div but I keep getting an error?
@DW_0505: yeah there is no operator.div. It is either operator.floordiv or operator.truediv (see here for a list of operators).
Thank you for your help!
4

You can use eval if you are absolutely certain that what you are passing to it is safe like so:

num1 = 4
num2 = 2
operators = ['+','-','*','/']
op = random.choice(operators)
res = eval(str(num1) + op + str(num2))

Just keep in mind that eval executes code without running any checks on it so take care. Refer to this for more details on the topic when using ast to do a safe evaluation.

11 Comments

eval(..) is considered dangerous. You better avoid it, unless you have absolutely no choice.
@WillemVanOnsem Agreed. I'm just providing an answer with the given parameters :)
@Ev.Kounis literal_eval won't work with all operators, try ast.literal_eval('2*3'); I'm actually surprised it works with + and -
@Chris_Rands It seems that in some cases, additions and subtractions also fail. See the link above,
@Ev.Kounis Thanks, also see: stackoverflow.com/questions/40584417/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.