1

I am taking a integer input from a function and the operation such as "+10" from the user and printing the result after computation. So far i have this

def Eval(arg1, arg2):

    if (arg1 >= 100):
        arg1 == 100
    else:
        arg1 = eval((arg1)(arg2))
        print arg1
Eval(10,'+10')

But I have TypeError: 'int' object is not callable error. Can someone tell me where i am doing wrong?

2 Answers 2

1

You can use ast.literal_eval. This is recommended instead of eval due to security concerns.

from ast import literal_eval

def Eval(arg1, arg2):

    if (arg1 >= 100):
        arg1 == 100

    return literal_eval(str(arg1)+arg2)

x = raw_input('Append string to variable for calculation:\n')  # '+10'
res = Eval(10, x)

print res  # 20
0
0

The issue comes from attempting to pass eval an int and a str when it only accepts a str. You could solve this by combining arg1 and arg2, after converting arg1 to a str.

arg1 = 10
arg2 = '+1'
evalInput = str(arg1) + arg2
eval(evalInput)
>> 11

This could be made cleaner by using string formatting, but this should give you a general idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.