0

I am creating an application than can solve expressions. Here is my code:

import parser

def evaluate_function(computation):
    parsed_expression = parser.expr(str(computation).strip()).compile()
    parsed_expression = complex(eval(computation))
    return parsed_expression

def plot_and_evaluate_function():

    print("Example: 2 * x + 1; sin(x); diff(cos(x) + 2 * sin(x + 1), x); limit(1/x, x, oo); x + 6")
    function = input("Write a function or set of functions seperated by semicolons: ")
    print("")

    function = function.replace("^", "**")

    function = function.split(";")

    function_outputs = []

    for i in range(len(function)):
        result = function[i]
        function_outputs.append(result)

    print("")
    print("Example: x = 10; y = 9; 17 = z")
    variable = input("Assign a value for each variable: ")
    print("")

    variable = variable.split(";")

    for i in range(len(variable)):
        variable[i] = exec(str(variable[i]).strip())

    solution_outputs = []

    for i in range(len(function_outputs)):

        solution = evaluate_function(str(function_outputs[i]))
        solution_outputs.append(solution)

    print("Answer(s): " + str(solution_outputs))
    print("")

plot_and_evaluate_function()

The code does not work; however, when I remove the plot_and_evaluate_function() function, it works. I do not know what is going on.

The specific issue I have is NameError: name 'x' is not defined. However, this issue does not exist when the code in plot_and_evaluate_function() is not contained within a function. What is happening?

Edit: I have tried adding these lines of code to the loop that starts with for i in range(len(variable))::

ldict = {}
variable[i] = exec(str(variable[i]).strip(), globals(), ldict)
x = ldict["x"]

This did not work.

  • Possible duplicate https://stackoverflow.com/questions/1463306/how-does-exec-work-with-locals – Mazdak Dec 13 '20 at 14:13
  • If I copy and paste your example code, and run it using the examples. I do not get the `NameError`, but a `SyntaxError: cannot assign to literal`, because `17 = z`. Resolving, that and checking you `computation` variable, you get `2 * x + 1`, you still have to replace the variables by the actual value. – Thymen Dec 13 '20 at 14:43
  • @Kasravnd That did not work. – PythonProgrammer314 Dec 16 '20 at 14:58

0 Answers0