Skip to content
Advertisement

How to use string symbols like x,y as undefined variable in calculations in Python?

I will try to explain what I want to do:

I will some polynomial approximation calculations in Python. And my aim is not to use numbers. I want to work with the symbols like x,y,c etc. But I couldn’t find any way to use them in calculations. Simply I want to do that:

x=c1
y=c2

These x and y are my variables in the script.

x+y
print(x+y)

When I did print(x+y), I want to see c1+c2 on the screen. In the same way,

2*x
print(2*x)

When I did print(2*x), I want to see 2c1 or 2*c1 on the screen. The same conditions should be valid for multiply and subtraction.

Can I do in Python and which library or function that I should use?

Advertisement

Answer

You should try sympy. It does what you want:

import sympy as sym
c1 = sym.Symbol('c1')
c2 = sym.Symbol('c2')
x=c1
y=c2

print(x+y)

print(2*x)

Output

c1 + c2
2*c1
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement