I started working on my first Python code today and got the basis of my program working okay until I tried to take user input. A simple example:
import numpy
A = set()
max = 10**3;
def f(k):
return 2*k 1
g = (f(k) for k in range(max));
A.update(g);
print("A = ", A)
It's just filling a set. It works fine (except for being extremely slow) until I try to let input data define the function:
func = input("Input a function: ")
def f(k):
return func
g = (f(k) for k in range(max));
A.update(g);
print("A = ", A)
This returns A = {'2*k 1'}
, if I give it 2*k 1 as input.
How do I get it to work like my original code with user input? I have found some examples here and elsewhere regarding similar problems, but in those cases there where trig functions involved and I must keep floats away from this code =)
I am using Python 3.9 in PyCharm 2021.2.2 (Community Edition), in case that that info is relevant.
CodePudding user response:
input()
does always return a string. So, the f(k)
function is always returning the string that was inputed, not the result of the code inside that string. You should use eval(func)
in the defenition of f(k)
instead.
Note: The use of eval
can cause any malicious code in the input to be executed. So, only use it when you can control the input completely and there are no other ways of doing it.
I would also recommend to use range(1,max 1)
, such that you get the answers for 1 to max instaed of 0 to max -1. (range never includes the ending value)
In the code that is given, the numpy module is not used. If nothing of your further code uses it, you can remove the import.
CodePudding user response:
you could pass the definition of the function as an input using the python lambda function. Run below code, and pass f = lambda x: 2*x 1
as input, you will see result 5 got printed.
func = input("Input a function: ")
exec(func)
print(f(2))
you could also get the function name by parsing from the input string, and running with it with the globals.
func = input("Input a function: ")
exec(func)
function_name = func.split('=')[0].strip()
func_to_run = globals()[function_name]
print(func_to_run(2))