Python specifying function as input [duplicate]











up vote
0
down vote

favorite













This question already has an answer here:




  • how to define a function from a string using python

    4 answers




import math

def g(x):
return x**2+3

def Integrate(f, a , b, n):
h=(b-a)/n
result=0
for k in range(n):
x=k*h+h/2
result+=f(x)*h
return result

F=input("f:")
A=float(input("a:"))
B=float(input("b:"))
N=int(input("n:"))
print(Integrate(F, A, B, N))


Whenever i try to run this code, it reads F to be a string and gives an error when called in integrate(f, a, b, n). I found that there is no way in python to define F as a function, but calling a function in another function is definitely possible. Then how can i still pull this way of using an input to specify what function to use off?



error:



 line 14, in Integrate
result+=f(x)*h
TypeError: 'str' object is not callable









share|improve this question







New contributor




Sander Kronemeijer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











marked as duplicate by Chris_Rands python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • @VasilisG. I'm pretty sure OP wants f(x), to evaluate the function f at the point x in order to estimate the integral.
    – pkpnd
    2 days ago










  • Could you provide some example input data for your problem?
    – Vasilis G.
    2 days ago










  • probably quite tricky to do this securely, you'd need to write a parser. A non-secure way (NOT for external use) would be exec(F), now if input("f:") was F = lambda x: x * 2 you will have a working function
    – Chris_Rands
    2 days ago















up vote
0
down vote

favorite













This question already has an answer here:




  • how to define a function from a string using python

    4 answers




import math

def g(x):
return x**2+3

def Integrate(f, a , b, n):
h=(b-a)/n
result=0
for k in range(n):
x=k*h+h/2
result+=f(x)*h
return result

F=input("f:")
A=float(input("a:"))
B=float(input("b:"))
N=int(input("n:"))
print(Integrate(F, A, B, N))


Whenever i try to run this code, it reads F to be a string and gives an error when called in integrate(f, a, b, n). I found that there is no way in python to define F as a function, but calling a function in another function is definitely possible. Then how can i still pull this way of using an input to specify what function to use off?



error:



 line 14, in Integrate
result+=f(x)*h
TypeError: 'str' object is not callable









share|improve this question







New contributor




Sander Kronemeijer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











marked as duplicate by Chris_Rands python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • @VasilisG. I'm pretty sure OP wants f(x), to evaluate the function f at the point x in order to estimate the integral.
    – pkpnd
    2 days ago










  • Could you provide some example input data for your problem?
    – Vasilis G.
    2 days ago










  • probably quite tricky to do this securely, you'd need to write a parser. A non-secure way (NOT for external use) would be exec(F), now if input("f:") was F = lambda x: x * 2 you will have a working function
    – Chris_Rands
    2 days ago













up vote
0
down vote

favorite









up vote
0
down vote

favorite












This question already has an answer here:




  • how to define a function from a string using python

    4 answers




import math

def g(x):
return x**2+3

def Integrate(f, a , b, n):
h=(b-a)/n
result=0
for k in range(n):
x=k*h+h/2
result+=f(x)*h
return result

F=input("f:")
A=float(input("a:"))
B=float(input("b:"))
N=int(input("n:"))
print(Integrate(F, A, B, N))


Whenever i try to run this code, it reads F to be a string and gives an error when called in integrate(f, a, b, n). I found that there is no way in python to define F as a function, but calling a function in another function is definitely possible. Then how can i still pull this way of using an input to specify what function to use off?



error:



 line 14, in Integrate
result+=f(x)*h
TypeError: 'str' object is not callable









share|improve this question







New contributor




Sander Kronemeijer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












This question already has an answer here:




  • how to define a function from a string using python

    4 answers




import math

def g(x):
return x**2+3

def Integrate(f, a , b, n):
h=(b-a)/n
result=0
for k in range(n):
x=k*h+h/2
result+=f(x)*h
return result

F=input("f:")
A=float(input("a:"))
B=float(input("b:"))
N=int(input("n:"))
print(Integrate(F, A, B, N))


Whenever i try to run this code, it reads F to be a string and gives an error when called in integrate(f, a, b, n). I found that there is no way in python to define F as a function, but calling a function in another function is definitely possible. Then how can i still pull this way of using an input to specify what function to use off?



error:



 line 14, in Integrate
result+=f(x)*h
TypeError: 'str' object is not callable




This question already has an answer here:




  • how to define a function from a string using python

    4 answers








python string function callable






share|improve this question







New contributor




Sander Kronemeijer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




Sander Kronemeijer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




Sander Kronemeijer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 2 days ago









Sander Kronemeijer

6




6




New contributor




Sander Kronemeijer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Sander Kronemeijer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Sander Kronemeijer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




marked as duplicate by Chris_Rands python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by Chris_Rands python
Users with the  python badge can single-handedly close python questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • @VasilisG. I'm pretty sure OP wants f(x), to evaluate the function f at the point x in order to estimate the integral.
    – pkpnd
    2 days ago










  • Could you provide some example input data for your problem?
    – Vasilis G.
    2 days ago










  • probably quite tricky to do this securely, you'd need to write a parser. A non-secure way (NOT for external use) would be exec(F), now if input("f:") was F = lambda x: x * 2 you will have a working function
    – Chris_Rands
    2 days ago


















  • @VasilisG. I'm pretty sure OP wants f(x), to evaluate the function f at the point x in order to estimate the integral.
    – pkpnd
    2 days ago










  • Could you provide some example input data for your problem?
    – Vasilis G.
    2 days ago










  • probably quite tricky to do this securely, you'd need to write a parser. A non-secure way (NOT for external use) would be exec(F), now if input("f:") was F = lambda x: x * 2 you will have a working function
    – Chris_Rands
    2 days ago
















@VasilisG. I'm pretty sure OP wants f(x), to evaluate the function f at the point x in order to estimate the integral.
– pkpnd
2 days ago




@VasilisG. I'm pretty sure OP wants f(x), to evaluate the function f at the point x in order to estimate the integral.
– pkpnd
2 days ago












Could you provide some example input data for your problem?
– Vasilis G.
2 days ago




Could you provide some example input data for your problem?
– Vasilis G.
2 days ago












probably quite tricky to do this securely, you'd need to write a parser. A non-secure way (NOT for external use) would be exec(F), now if input("f:") was F = lambda x: x * 2 you will have a working function
– Chris_Rands
2 days ago




probably quite tricky to do this securely, you'd need to write a parser. A non-secure way (NOT for external use) would be exec(F), now if input("f:") was F = lambda x: x * 2 you will have a working function
– Chris_Rands
2 days ago












2 Answers
2






active

oldest

votes

















up vote
0
down vote













You can input a function on the console by using a lambda (as a string), and use eval to convert the string to an actual function object. Your code would look like this:



F = eval(input("f:"))


On the console, if you want to integrate the function f(x) = 2 * x + 1, you'd input:



lambda x: 2 * x + 1


as a string. However, note that eval will execute (as Python code) whatever you input on the console, and this could be a security concern depending on how your program is used.






share|improve this answer




























    up vote
    -1
    down vote













    I don't know if you want to use function from math module, but if yes then you can obtain method from module by string like this:



    function_to_call = getattr(math, f)
    result += function_to_call(x) * h


    When doing this you should surround with try except block to check if given function name exit in math module.






    share|improve this answer





















    • This only works if the function to integrate is defined in the math module. This would not work for an arbitrary function like f(x) = 2*x.
      – pkpnd
      2 days ago


















    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    You can input a function on the console by using a lambda (as a string), and use eval to convert the string to an actual function object. Your code would look like this:



    F = eval(input("f:"))


    On the console, if you want to integrate the function f(x) = 2 * x + 1, you'd input:



    lambda x: 2 * x + 1


    as a string. However, note that eval will execute (as Python code) whatever you input on the console, and this could be a security concern depending on how your program is used.






    share|improve this answer

























      up vote
      0
      down vote













      You can input a function on the console by using a lambda (as a string), and use eval to convert the string to an actual function object. Your code would look like this:



      F = eval(input("f:"))


      On the console, if you want to integrate the function f(x) = 2 * x + 1, you'd input:



      lambda x: 2 * x + 1


      as a string. However, note that eval will execute (as Python code) whatever you input on the console, and this could be a security concern depending on how your program is used.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        You can input a function on the console by using a lambda (as a string), and use eval to convert the string to an actual function object. Your code would look like this:



        F = eval(input("f:"))


        On the console, if you want to integrate the function f(x) = 2 * x + 1, you'd input:



        lambda x: 2 * x + 1


        as a string. However, note that eval will execute (as Python code) whatever you input on the console, and this could be a security concern depending on how your program is used.






        share|improve this answer












        You can input a function on the console by using a lambda (as a string), and use eval to convert the string to an actual function object. Your code would look like this:



        F = eval(input("f:"))


        On the console, if you want to integrate the function f(x) = 2 * x + 1, you'd input:



        lambda x: 2 * x + 1


        as a string. However, note that eval will execute (as Python code) whatever you input on the console, and this could be a security concern depending on how your program is used.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 2 days ago









        pkpnd

        4,5171139




        4,5171139
























            up vote
            -1
            down vote













            I don't know if you want to use function from math module, but if yes then you can obtain method from module by string like this:



            function_to_call = getattr(math, f)
            result += function_to_call(x) * h


            When doing this you should surround with try except block to check if given function name exit in math module.






            share|improve this answer





















            • This only works if the function to integrate is defined in the math module. This would not work for an arbitrary function like f(x) = 2*x.
              – pkpnd
              2 days ago















            up vote
            -1
            down vote













            I don't know if you want to use function from math module, but if yes then you can obtain method from module by string like this:



            function_to_call = getattr(math, f)
            result += function_to_call(x) * h


            When doing this you should surround with try except block to check if given function name exit in math module.






            share|improve this answer





















            • This only works if the function to integrate is defined in the math module. This would not work for an arbitrary function like f(x) = 2*x.
              – pkpnd
              2 days ago













            up vote
            -1
            down vote










            up vote
            -1
            down vote









            I don't know if you want to use function from math module, but if yes then you can obtain method from module by string like this:



            function_to_call = getattr(math, f)
            result += function_to_call(x) * h


            When doing this you should surround with try except block to check if given function name exit in math module.






            share|improve this answer












            I don't know if you want to use function from math module, but if yes then you can obtain method from module by string like this:



            function_to_call = getattr(math, f)
            result += function_to_call(x) * h


            When doing this you should surround with try except block to check if given function name exit in math module.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 2 days ago









            Rafał Duraj

            12




            12












            • This only works if the function to integrate is defined in the math module. This would not work for an arbitrary function like f(x) = 2*x.
              – pkpnd
              2 days ago


















            • This only works if the function to integrate is defined in the math module. This would not work for an arbitrary function like f(x) = 2*x.
              – pkpnd
              2 days ago
















            This only works if the function to integrate is defined in the math module. This would not work for an arbitrary function like f(x) = 2*x.
            – pkpnd
            2 days ago




            This only works if the function to integrate is defined in the math module. This would not work for an arbitrary function like f(x) = 2*x.
            – pkpnd
            2 days ago



            Popular posts from this blog

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Insert data from modal to MySQL (multiple modal on website)