简体   繁体   中英

Function value calculated through user input

Hey Stack Overflow Community, I have a specific question to my Python code. The following application should calculate the functional values, after the user inputs the function, the interval and the step width of the x values. Now I have the problem, that I do not know, how to insert the the single x values into the function. I did it here for the function x^2 only, but it should work for many more individual user functions. So I do not have to initialise every single function and their calculation. Already thank you.

from math import sqrt

xv = []
y = []

def AddSpace (x):
    print ("\n" * x)


AddSpace (4)
func = input ("Funktion: ")
ug = input ("Untere Grenze: ")
og = input ("Obere Grenze: ")
sw = input ("Schrittweite: ")

#--------------------------------------
def x_werte(ug, og, sw):
    g = ug
    while (g >= ug and g <= og):
        xv.append (g)
        g += sw

x_werte (int (ug), int (og), float (sw))

#--------------------------------------

def y_werte ():
    if func == "x**2":
        for p in range (0, len (xv)):    
            y.append (float (xv [p])**2)  

You can create a dispatch table. You can do this with a Python dict . For example, suppose the functions are named x2 for x**2 and x3 for x**3 . You could define the dict as:

dispatch_dict = {
    "x2": do_x2,
    "x3": do_x3
}

The functions do_x2 and do_x3 would have to be defined before referencing them here. Then you can do:

if func not in dispatch_dict:
    print("No such function")
else:
    f = dispatch_dict[func]

You can then call f where you would call y_werte for instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM