Search code examples
pythonpython-3.xfunctionlimit

How to ask a user to input a function in python 3


i´m trying to make a program to find the limit of a function, however, i can´t find any effective way to ask the user to input a function, or convert any kind of user input into one, the best way i found was using: f= lambda n: eval(input("")
however, using this method, everytime i run into a loop, the user will be asked to input the function over and over, which in this case makes it unusable. I greetly apreciate any feedback Sorry if the post or my english is bad, i apoligize for it, i am new here and not a native english speaker, if it helps here is the complete code (with everything in french)

from lycee import *
n= int
# Rang actuel
f= lambda n: eval(input("veuillez introduire la fonction avec pour variable n"))
# Fonction introduite par l´usager
m= int(input("veuillez introduire la puisance de la valeur aussi grande, petite, ou proche que l´on veut"))
# Valeur max
l= int(input("veuillez introduire une limite eventuelle de la suite"))
d= int
# Prend une valeur selon la limite trouvé ou non
p= int(input("veuillez intoduire le pas"))
# Pas introduit par l´usager
x=int
# Valeur actuelle de la suite
n=1
d=0
x=0
#La limite est elle −∞?
while l>-10^m and n<10^15+1:
    n=n+p
    x=f(n)
    if n==10^15+1:
        print ("Après le calcul d’un billiard de termes, la suite ne semble pas tendre vers −∞")
    else:
        d=1
n=1
x=0
#La limite est elle +∞?
while l<10^m and n<10^15+1:
    n=n+p
    x=f(n)
    if n==10^15+1:
        print ("Après le calcul d’un billiard de termes, la suite ne semble pas tendre vers +∞")
    else:
        d=2
n=1
x=0
#La limite est elle l?
if l>=0:
    while x+l>10^-m and n<10^15+1:
        n=n+p
        x=f(n)
        if n==10^15+1:
            print ("Après le calcul d’un billiard de termes, la suite ne semble pas tendre vers l")
        else:
           d=3
else:
    while x-l>10^-m and n<10^15+1:
        n=n+p
        x=f(n)
        if n==10^15+1:
            print ("Après le calcul d’un billiard de termes, la suite ne semble pas tendre vers l")
        else:
            d=3
if d==1:
    print ("Après le calcul d’un billiard de termes, la suite semble avoir pour limite −∞")
else:
    if d==2:
        print ("Après le calcul d’un billiard de termes, la suite semble avoir pour limite +∞")
    else:
        if d==3:
            print ("Après le calcul d’un billiard de termes, la suite semble avoir pour limitel")
        else:
            print ("Après le calcul d’un billiard de termes, la suite semble ne pas avoir de limite")

Solution

  • You can use the compile function to compile the user's input into an AST object so that your lambda function can eval the AST object instead of asking the user for input again:

    func = compile(input("veuillez introduire la fonction avec pour variable n"), '<input>', 'eval')
    f = lambda n: eval(func)