I'm trying to insert a variable mathematical operator into a if statement, an example of what I'm trying to achieve in parsing user-supplied mathematical expressions:
maths_operator = "=="
if "test" maths_operator "test":
print "match found"
maths_operator = "!="
if "test" maths_operator "test":
print "match found"
else:
print "match not found"
obviously the above fails with SyntaxError: invalid syntax
. I've tried using exec and eval but neither work in an if statement, what options do I have to get around this?
Like in C, here we can't use arithmatic opration in condition part of if statement. Because in C the condition part is operation on integer values, like if result is zero then if statement's body is not executed and if it is 1 then it is executed.
With the in operator we see if some value contains another value. That is, x in s returns True when x is a member of s . When we use in with if statements, our code can tell if a string contains a substring, whether a list has a specific value, or if a dictionary has a certain key.
Use the operator package together with a dictionary to look up the operators according to their text equivalents. All of these must be either unary or binary operators to work consistently.
import operator
ops = {'==' : operator.eq,
'!=' : operator.ne,
'<=' : operator.le,
'>=' : operator.ge,
'>' : operator.gt,
'<' : operator.lt}
maths_operator = "=="
if ops[maths_operator]("test", "test"):
print "match found"
maths_operator = "!="
if ops[maths_operator]("test", "test"):
print "match found"
else:
print "match not found"
Use the operator
module:
import operator
op = operator.eq
if op("test", "test"):
print "match found"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With