Save user typed equation in python

Asked

Viewed 164 times

0

How could I save a math equation typed by the user and then replace values in this equation?

EX: User typed: "3*x+2" then the program replaces "x" with 1, showing at the end the value 5 (3*1+2)

1 answer

3


There is a Python library for algebra, the name is Sympy. It is very simple to use, in this example there, would be:

from sympy import *
x = Symbol('x')
expr = expand(input())
num = int(input())
res = expr.subs(x, num)
print(res)

To install sympy just use the pip3 install sympy command

  • He wants the result of the equation out, his program does it?

  • Yes, the user type the expression in one line and in the other type the value of variable x. See the Sympy documentation link for more information, you can define more variables, if applicable.

  • got it, good solution!

  • Thank you very much Lorenzo, I was using Symbol() instead of expand() to save the user-typed equation and it wasn’t working. Your code worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.