Search code examples
pythoncalculus

IVT Theorem Calculator in Python


I am having a problem.

def f(x):
    function = input("Enter yoru Function: ")
    return function


a = -1
b = 2
a_Applied = f(a)
b_Applied = f(b)

if a_Applied < 0 and b_Applied > 0:
    print "IVT Applies."
elif a_Applied > 0 and b_Applied < 0:
    print "IVT Applies"
else:
    print "IVT Does Not Apply"

This is my current code. I am trying to let the user make a function in line 2. However this breaks the program because it is a string. How do I get it to not be a string, and instead for it to be able to take a function.

Ex.

User inputs "2*x + 1" In a perfect world the program then runs 2(a) +1 and 2(b) + 1 and then compares them using the if statement. Because the input is a string ti doesn't work.

Any help?


Solution

  • Use lambda expression and eval function. Like this.

    def read_user_function():
        function_str = input("Enter your Function: ")
        return lambda x: eval(function_str, { 'x' : x })
    

    Call user function by

    f = read_user_function()
    print(f(2))
    

    Here is a demo https://repl.it/ITuU/2.

    Explanation

    The function above, read_user_function returns a lambda expression, basically a function, that will evaluate the user's input with the variable, sort of like a parameter, x set to the x value that is passed to the lambda expression. This can get confusing if your new to this sort of thing but just think of read_user_function as returning an anonymous function that accepts a single argument and its body equals eval(function_str, { 'x' : x })

    Warning

    This is a quick and dirty solution to evaluating mathematical expression. The function would execute any valid python code and not only mathematical expression. This may be dangerous if your application is sensitive - you wouldn't want the user executing custom code.