P
P
Pproger_122018-08-31 19:01:59
Python
Pproger_12, 2018-08-31 19:01:59

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

3 answer(s)
K
Kirill Stryaponoff, 2018-08-31
@Pproger_12

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.

K
Konstantin Malyarov, 2018-08-31
@Konstantin18ko

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545

A
a458312, 2020-06-03
@a458312

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 question

Ask a Question

731 491 924 answers to any question