0

Ok, so I'm trying to create a function in Python named calc that can perform the 4 basic arithmetic operations.

def calc(n, num1, num2):

    if n == '+':
        return num1 + num2

    elif n == '-':
        return num1 - num2

    elif n == 'x':
        return num1 * num2

    elif n == '/':
        return num1 / num2

This is my code so far. So when I execute it like so, I get a syntax error pointing to the number 6, the 3rd argument to be passed.

calc(+ 4 6)

SyntaxError: invalid syntax

Can someone tell me what's wrong? I'm just now learning python and I'm expected to create an Interpreter with loops, conditions, functions and variable assignments so getting stuck on this makes me somewhat frustrated, any help is appreciated.

Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37

1 Answers1

0

You can't make a function which would handle this:

calc(+ 4 6)

That is invalid syntax.

But you could do this:

calc('+', 4, 6)

You function would already work with it.

Or you could have this:

calc('+ 4 6')

and then a function which has to parse the contents.

zvone
  • 18,045
  • 3
  • 49
  • 77
  • Thank you so much. I actually tried calc('+' 4 6) and calc(+,4,6) earlier to no avail. Who knew putting them together was the answer. I'm still new to python so I'm not really familiar with the syntax, tnx for the help. – Timothy Subito Sep 11 '16 at 11:17
  • You're welcome. Of course... putting them together as `calc('+ 4 6')` means that `calc` takes one argument, which it has to `split` and then has to convert two of them to `int` (or `long` or `float`, or whatever)... – zvone Sep 11 '16 at 11:20