0

This is just a general question as I am curious. When I run the following code I get a syntax error which is understandable. However would there be a way to save the + sign in an variable so I get an answer of 4?

SIGN = +
UNIT = 1
UNIT2 = 3
print(UNIT SIGN UNIT2)
Spencer
  • 5
  • 5
  • You generally can't, as `+` is part of the language and not an object. You can however play around with strings and use a library like `sympy` to evaluate. – Moses Koledoye May 28 '17 at 23:06
  • You can not store arithmetic operator in the variable, however as a workaround you may store the operator as string and achieve the desired result following the answers in the linked questions – Moinuddin Quadri May 28 '17 at 23:08

1 Answers1

0

You can make a function for the + operator:

def add(a, b):
    return a + b

and store it:

operation = add
unit = 1
unit2 = 3

print(operation(unit, unit2))

Functions for operators are even built into Python:

from operator import add
Ry-
  • 218,210
  • 55
  • 464
  • 476