Taha El Almi
Taha El Almi

Reputation: 3

Asking the user to enter a function in python

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)

Upvotes: 0

Views: 120

Answers (1)

Arun
Arun

Reputation: 180

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)

Upvotes: 1

Related Questions