0

I am making a python program that computes the solution of f(x) =0 with Newton method, for any function. Is it possible to ask the user to enter the function?

my pseudo code :

# ask for a function # create a function with: def Newton(Myfunction, initial_value) 
2
  • The user could create a function e.g. def f(): return None and then assign it to a variable my_func = f and then pass the variable to your program (or simply pass f). Commented Jan 3, 2020 at 9:42
  • Please check the edit in the answer below. Commented Jan 3, 2020 at 10:31

1 Answer 1

1

You can ask the user to input the name of the python file that contains the function definition and also ask for the name of the function. Then inside your main file you can do

import importlib source = importlib.import_module(filename) func = getattr(source, function) 

like in this answer where function is the name of your user function and then call the function from your main file. You can take user input as

filename = input("Please enter filename containing function") 

However there's a security risk in this method as the user can input any function from the file this way (as noted in the comment below)

Sign up to request clarification or add additional context in comments.

1 Comment

I assume this method will allow for arbitrary execution of code in your program. If so, it's worth mentioning the security risk in the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.