Answer the question
In order to leave comments, you need to log in
How to enter a mathematical expression in Python?
I wrote a program that builds graphs of two variables, but I need to organize it so that the function is not clogged in the program, but the user enters it. I tried to do this but it doesn't work because the input returns a string and not a mathematical expression. How should it be properly organized?
Answer the question
In order to leave comments, you need to log in
That's right - the user enters exactly the string, and then you need to parse it: separate the numbers and mathematical operators and, depending on this, manipulate the numbers. The task is a little more difficult than you imagine.
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
import numpy as np
import matplotlib.pyplot as plt
eqn = input()
y_list = []
x_list = np.linspace(-10, 10, 201)
for x in range(len(x_list)):
eqn_list = list(eqn)
for i in range(0, len(eqn_list)):
if eqn_list[i] == 'x':
eqn_list[i] = str(x_list[x])
y = ''.join(eqn_list)
print(eval(y), x_list[x])
y_list.append(eval(y))
plt.grid()
plt.plot(x_list, y_list)
plt.show()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question