How to receive a user value to be calculated in a function using Sympy?

Asked

Viewed 72 times

0

I am using the Python Sympy Library, however, I did not find a way to calculate the result of a function using it, IE, I have my function that will be typed by the user, and the value of x that will also be typed by him. ex: function = x + 10 and my value of x = 2. I want the return of 12, but this is what I did not find how to do in your documentation. My Attempt:

from sympy import *

E = input("função ?  ")
x = int(input("Digite o valor de x "))
SimboloX = ('x')
R = solve(function(E,x),SimboloX)
print(R)

1 answer

1


You can use the function sympy.parsing.sympy_parser.parse_expr:

from sympy.parsing.sympy_parser import parse_expr

expr = input('Qual é a expressão em x? ')
x = int(input('E qual é o valor de x? '))

expression = parse_expr(expr)
result = expression.subs('x', x)

print(f'O resultado de {expr} para x={x} é {result}')

Sample output:

> Qual é a expressão em x? x + 2
> E qual é o valor de x? 10
O resultado de x + 2 para x=10 é 12

Browser other questions tagged

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