Home > Mobile >  Cannot pass string variable to function to use eval
Cannot pass string variable to function to use eval

Time:10-10

I'm trying to use eval built in function within my function, if I do eval(text) or eval("x * 2 (x 5)") it could return the calculation but when I pass the text to my function it said TypeError: can only concatenate str (not "int") to str. I already cast it to string but still no avail

x = 1
text = "x * 2   (x   5)"

def test_func(x):
    res = eval(x)
    return res

test_func(text)

CodePudding user response:

the argument x of the test_func is assumed to be an integer becasue you decalare before x=1. If you rename the argument it works:

x = 1
text = "x * 2   (x   5)"


def test_func(my_eval_string):
    res = eval(my_eval_string)
    return res

CodePudding user response:

You are passing 'x' instead of 'text'. Please check below one:

x = 1
text = "x * 2   (x   5)"

def test_func(text):
    res = eval(text)
    return res

print(test_func(text))
  • Related