Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python if-statement with variable mathematical operator

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 image 750
binhex Avatar asked Aug 07 '12 13:08

binhex


People also ask

Can we use arithmetic operators in IF statement?

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.

Can we use in operator in if statement in Python?

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.


2 Answers

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"
like image 86
Nathan Avatar answered Oct 26 '22 23:10

Nathan


Use the operator module:

import operator
op = operator.eq

if op("test", "test"):
   print "match found"
like image 29
Mark Byers Avatar answered Oct 27 '22 01:10

Mark Byers