Kannan Sethu
Kannan Sethu

Reputation: 31

How can I perform arithmetic operation taking a integer and string as input

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?

Upvotes: 1

Views: 161

Answers (2)

lpbearden
lpbearden

Reputation: 148

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.

Upvotes: 0

jpp
jpp

Reputation: 164613

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

Upvotes: 1

Related Questions