1

I am stuck on how to make a calculation in a variable. Currently my code will print (for example) : (1,'+',2). But I need the actual sum of the answer.. My code:

def calc(num1,op,num2):
    sum = num1,op,num2
    print(sum)

num1 = int(input("First number:"))
op = input("Operator:")
num2 = int(input("Second number:"))

calc(num1,op,num2)
  • I think it's not an evidence for OP that it is a duplicate. the key is that `+` (the symbol) and `add` (the function) are different things. – B. M. Feb 29 '16 at 19:43

1 Answers1

0

This can help you.....

def calc(x=0, y=0, z=0):
    expression = raw_input('Enter an expression: ')

    return eval(expression, None, locals())

Example:

>>> calc()
Enter an expression: 8 + 5 - 7
6
AmanKumar
  • 1,333
  • 2
  • 20
  • 33
  • `eval` is really not a good choice here. This is a good explanation that might interest you: http://stackoverflow.com/a/1832957/1832539 – idjaw Feb 29 '16 at 19:20