Paul85
Paul85

Reputation: 657

Conditional if statement in python

Instead of writing long 'if' statement, I would like to store that in some variable then pass it into 'if' condition. For example:

tempvar = '1 >0 and 10 > 12'
if tempvar:
   print something
else:
     do something

Does it possible in python ?

Thanks for your suggestion but my problem is something else which I can't figure out. I am doing multi string search in text file and trying to convert multi string into one condition:

    allspeciesfileter=['Homo sapiens', 'Mus musculus', 'Rattus norvegicus' ,'Sus scrofa']
    multiequerylist=[]

    if len(userprotein)> 0:
        multiequerylist.append("(str("+ "'"+userprotein+ "'"+")).lower() in (info[2].strip()).lower()")
    if len(useruniprotkb) >0:
        multiequerylist.append("(str("+ "'"+useruniprotkb+ "'"+")).lower() in (info[3].strip()).lower()")
    if len(userpepid) >0:
        multiequerylist.append("(str("+ "'"+userpepid+ "'"+")).lower() in (info[0].strip()).lower()")
    if len(userpepseq) >0:
        multiequerylist.append("(str("+ "'"+userpepseq+ "'"+")).lower() in (info[1].strip()).lower()")


    multiequery =' and '.join(multiequerylist)

    for line in pepfile:
        data=line.strip()
        info= data.split('\t')
        tempvar = bool (multiquery)
        if tempvar:
           do something

But that multiquery is not working

Upvotes: 1

Views: 221

Answers (3)

yoniLavi
yoniLavi

Reputation: 2752

I would highly recommend avoiding this in production code, due to performance, security and maintenance issues, but you can use eval to convert your strings to an actual bool value:

string_expression = '1 >0 and 10 > 12'
condition = eval(string_expression)
if condition:
   print something
else:
   do something

Upvotes: 1

Pythonista
Pythonista

Reputation: 11645

Just drop the string and store the condition in the variable.

>>> condition = 1 > 0 and 10 > 12
>>> if condition:
...    print("condition is true")
... else:
...    print("condition is false")
...
condition is false

You can even store a more complex condition with (for example) lambda

Here's random example using lambda with something a little more complex

(although using BS for parsing this is a bit overkill)

>>> from bs4 import BeautifulSoup
>>> html = "<a href='#' class='a-bad-class another-class another-class-again'>a link</a>"
>>> bad_classes = ['a-bad-class', 'another-bad-class']
>>> condition = lambda x: not any(c in bad_classes for c in x['class'])
>>> soup = BeautifulSoup(html, "html.parser")
>>> anchor = soup.find("a")
>>> if anchor.has_attr('class') and condition(anchor):
...    print("No bad classes")
... else:
...    print("Condition failed")
Condition failed

Upvotes: 6

Aaron
Aaron

Reputation: 29

>>> 1 > 0 and 10 > 12
False
>>> '1 > 0 and 10 > 12'
'1 > 0 and 10 > 12'
>>> stringtest = '1 > 0 and 10 > 12'
>>> print(stringtest)
1 > 0 and 10 > 12
>>> if stringtest:
...     print("OK")
... 
OK
>>> 1 > 0 and 10 < 12
True
>>> booleantest = 1 > 0 and 10 < 12
>>> print(booleantest)
True
>>>

The string type is True. You should drop the single quotes.

Upvotes: 0

Related Questions