Can you make a variable into an equation so it can be solved?
A simple example would be something like
equ = "23/(n+2)"
for n in range(2):
ans = equ
print ans
This returns
23/(n+2)
23/(n+2)
Rather than the desired
11.5
7.667
Can you make a variable into an equation so it can be solved?
A simple example would be something like
equ = "23/(n+2)"
for n in range(2):
ans = equ
print ans
This returns
23/(n+2)
23/(n+2)
Rather than the desired
11.5
7.667
You could use SymPy for this:
from sympy import sympify, Symbol
equ = "23/(n+2)"
equ_ = sympify(equ)
n_ = Symbol('n')
for n in range(2):
print equ_.subs({n_: n}).evalf()
Note: eval is really dangerous.
You could use eval()
:
equ = "23/(n+2)"
for n in range(2):
ans = equ
print eval(ans)
Note that this will give incorrect results in Python 2 (11 and 7 respectively). In Python 3 it would give the correct result. You can fix that in Python 2 by making sure at least one involved number is not an integer:
equ = "23.0/(n+2)"
for n in range(2):
ans = equ
print eval(ans)