Get conditional string value: True or False

I have a conditional string like below,

condition1 = "((2=2) or (3=1)) and (1=1)"
condition2 = "((2=3) or (1=1)) and (4=5)"

      

Above, both conditions give me the output of True and False respectively.

Additional explanations:

condition1 works like,

if ((2==2) or (3==1)) and (1==1):
      Return True
else:
      Return False

      

Output for condition 1: True

condition2 works like,

if ((2==3) or (1==1)) and (4==5):
      Return True
else:
      Return False

      

Output for condition2: True

Update:

Sorry friends

I have a conditional string like above condition1 and condition2.

I want to make a function when I parse a condition as a string and this function executes as if - else and returns a boolean

Please, help...

Thanks Chintan

+3


source to share


4 answers


Warning: Use is eval

potentially dangerous and you should never validate untrusted input (like any kind of user input).



In [1]: condition1 = "((2=2) or (3=1)) and (1=1)"
   ...: condition2 = "((2=3) or (1=1)) and (4=5)"
   ...: 

In [2]: eval(condition1.replace('=','=='))
Out[2]: True

In [3]: eval(condition2.replace('=','=='))
Out[3]: False

      

+3


source


If you are wondering how to get a condition and give python to output True or False, have a look at the eval () function in python.



+2


source


In python, the comparison operator ==

.

In any case, you should be more clear about what we should help with if it does not solve your problem.

Update: The function you are looking for to evaluate a string representing a Python expression is eval()

.

+1


source


solution without 'eval'

def condition(a,b,c):  
    if (((a[0]==a[1]) or (b[0]==b[1])) and (c[0]==c[1])):  
       return True  
    else:  
      return False

      

print condition ((2,2), (3,1), (1,1)) # returns True print condition ((2,3), (1,1), (4,5)) # returns False

+1


source







All Articles