1

Suppose I have this code:

int1 = (2 + 2) * 4
print(int1)

OUTPUT: 16

But is there a way to print the math of the int without using a string instead? Like a literal() function or something?

Example program:

int1 = 2 + 2
int2 = 4

print('{} times {} equals:'.format(literal(int1), literal(int2))
print(int1 * int2)

OUTPUT:
2 + 2 times 4 equals:
16

I kind of feel like I'm looking for a solution to a problem that doesn't exist, but I'm new to Python and I'm curious.

Red
  • 26,798
  • 7
  • 36
  • 58
leftbones
  • 113
  • 1
  • 7
  • I don't think there is a function for that, however it should be easy for you to create your own – Ismail Hafeez Jan 29 '21 at 18:13
  • The more straight-forward approach would be to use strings, and then evaluate them. Using `eval` wouldn't be unsafe unless you were getting your strings from untrusted inputs, if they are from the source code it's fine. So, `expression = "2 + 2"; result = eval(expression);`. If the strings do come from untrusted input, then you can use a simple parser written with the pyparsing library: https://stackoverflow.com/a/2371789/5014455 – juanpa.arrivillaga Jan 29 '21 at 18:19
  • 3
    But what you *may* really be looking for is a "computer algebra system", a popular library for this is [sympy](https://docs.sympy.org/latest/tutorial/intro.html) – juanpa.arrivillaga Jan 29 '21 at 18:25
  • I suppose I may be looking at this backwards. Perhaps it makes more sense to create the string "2 + 2" and then pick that string apart to find the numbers, symbols, etc., and then do the math from there. – leftbones Jan 29 '21 at 21:47
  • If this is something you are doing in a Jupyter Notebook, look into using handcalcs. https://pypi.org/project/handcalcs/ – PaulMcG Feb 01 '21 at 03:14

4 Answers4

2

Native python 'forgets' the operations you made, and just remembers the values of the variables you have. So when you do x = int1 * int2, python allocates the corresponding value to x, but does not store anything about the operations which yielded this value.

However, it could be a (not so easy) coding exercise: design your own integer class which stores the history of computations.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
user122644
  • 109
  • 1
1
class Math():

    def __init__ (self):
        self.val = 0
        self.opList = []
    def add(self,val):
        self.val += val
        self.opList.append(" + "+str(val))
    def sub(self,val):
        self.val -= val
        self.opList.append(" - "+str(val))
    def printOps(self):
        print(self.val," = 0",end="")
        for i in self.opList:print(i,end="")

t = Math()

t.add(10)

t.sub(5)

t.printOps()

python does have operator overloading but it looks like a pain to write

  • Output would be 5 = 0 + 10 - 5 – Mofie The greate Jan 29 '21 at 19:16
  • Python absolutely *does* have operator overloading. See https://docs.python.org/3.9/reference/datamodel.html?highlight=__add__#emulating-numeric-types – PaulMcG Feb 01 '21 at 03:12
  • Used in this answer of mine from a few years back: https://stackoverflow.com/questions/7820771/python-number-like-class-that-remembers-arithmetic-operations/7844038#7844038 – PaulMcG Feb 01 '21 at 03:17
1

The more reasonable approach would be to use strings, and then evaluate them. Using eval wouldn't be unsafe unless you were getting your strings from untrusted inputs, if they are from the source code it's fine.

-- comment by juanpa.arrivillaga

int1 = '2 + 2'
int2 = '4'

print('{} times {} equals:'.format(int1, int2))
print(eval(int1) * eval(int2))

Output:

2 + 2 times 4 equals:
16
wjandrea
  • 28,235
  • 9
  • 60
  • 81
1

You can do something similar, except storing the literal firm in a string, and using the simple_eval method from the simpleeval module:

from simpleeval import simple_eval

int1 = '2 + 2'
int2 = 4

print('{} times {} equals:'.format(int1, int2))
print(simple_eval(int1) * int2)

Output:

2 + 2 times 4 equals:
16

simpleeval is a module that safely evaluates math expressions, as opposed to the infamous eval method, that allows malicious attacks to your OS.

Red
  • 26,798
  • 7
  • 36
  • 58
  • Interesting. I assume (without trying it) that you could also use simple_eval on ``int2`` and it would work just the same? – leftbones Jan 29 '21 at 21:51
  • Marking this as the answer! It maybe isn't the "best" way to do it, but it certainly makes the most sense to a beginner, and avoids the issues with ``eval``, which I wasn't even aware of. Now I have more reading material! – leftbones Jan 29 '21 at 21:53