1

I have a problem in python. I want to create an if clause from a string that is given as a parameter to a function. It looks something like this:

def function(foo)
   if(foo):
     print("bar")

test = "5 > 10"
function(test)

I would like to see nothing printed, because 5 > 10 is False. But actually it is printing "bar". Is there a way to get this right without asking if (foo.split(" ")[2] == ">") do something

3
  • 1
    looks like you need eval() Commented Jul 23, 2019 at 13:54
  • See also why you shouldn't use eval(). Even if it's more verbose, it's safer to do the if foo.split(" ")[1] == ">" thing you mentioned in your question. Commented Jul 23, 2019 at 13:57
  • 1
    thank you! with eval it works just fine =D Commented Jul 23, 2019 at 14:05

3 Answers 3

1

You could eval the foo argument:

def function(foo):
   if eval(foo):
     print("bar")
Sign up to request clarification or add additional context in comments.

Comments

1

Use eval()

Ex:

def function(foo):
    if(eval(foo)):
        print("bar")

test = "5 > 10"
function(test)

Comments

0

An "if" statement takes an expression and evaluate it. If the evaluation is 0 for a numerical expression, 'false' for a boolean expression or NULL for strings , it's considered as false expression and the "then" block is not executed. Otherwise, the expression is true.

In your case, a string's evaluation is always true because it's not NULL. the expression 5 > 10 is 'false', but the string "5 > 10" is 'true'.

You should use eval if you want to evaluate the string:

function(eval('5 >10'))

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.