Reputation: 109
Is there a simple way to show the equation of a var instead of the answer?
Example: add = 2 + 2
print("ADDITION: " + ?? + " = " + str(add))
Replace ?? with whatever to print:
ADDITION: 2 + 2 = 4
So that I can change the variable and it would still be correct?
Upvotes: 0
Views: 405
Reputation: 64398
You can store the expression as a string for the "variable representation" you want, and eval
it to get the "answer".
expr = '2 + 2'
print('ADDITION: %s = %s' % (expr, eval(expr))
However, "eval is evil", so use it with caution (e.g. don't eval
an expression you get as an input from the user).
Upvotes: 3
Reputation: 34186
You can try creating two variables:
a = 2
b = 3
then compute the sum:
add = 2 + 3
and print:
print("ADDITION: " + str(a) + " + " + str(b) + " = " + str(add))
or print it using format()
print("ADDITION: {} + {} = {}".format(a, b, add))
Upvotes: 0