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

Mureinik
  • 297,002
  • 52
  • 306
  • 350

3 Answers3

1

Use eval()

Ex:

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

test = "5 > 10"
function(test)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

You could eval the foo argument:

def function(foo):
   if eval(foo):
     print("bar")
Mureinik
  • 297,002
  • 52
  • 306
  • 350
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'))