0

I am trying to create a more complicated boolean function that I'll use between functions. Here is the simplified problem:

a = "1 == 2"

if a:
    print ("it is not working")
else:
    print ("it worked")

Out[1]:

it is not working

Basically I am trying to pass a function as a string and use that in a boolean later on but it turns out as True always.

I also tried:

bool(a)

Out[1]: True

6
  • "1 == 2" is a string... And any string that is not empty is 'truthy' in python... So that's why its always returning true... If you want 1 == 2 to be evaluated as a Boolean, remove the quotation marks around Commented Dec 25, 2019 at 20:58
  • a string is always true if its not None. This sounds like an XY problem. Normally its alwyas discouraged an approach like this where you want to eval a string. However if your insistant on it you should look up ast.literal_eval Commented Dec 25, 2019 at 20:58
  • Is the empty string in Python not evaluated to false? Commented Dec 25, 2019 at 21:01
  • @JordanSimba yeah sorry thats what i mean, string is always true unless its empty. Commented Dec 25, 2019 at 21:02
  • Try eval(a). For a = "1 == 2", eval(a) = False. For a = "1 == 1", eval(a) = True. More info on eval Commented Dec 25, 2019 at 21:11

1 Answer 1

1

Try eval

a = "1 == 2"
eval(a)
>>>False

a = "1 == 1"
eval(a) 
>>> True
Sign up to request clarification or add additional context in comments.

Comments

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.