Mar-25-2022, 07:42 PM
I do not understand what you are trying to do. Do you want to make a variable named "name1" that references a function? If so, why? What's wrong with the name "myfunction"? If you want the function to be called "name1" why didn't you name it that in the first place? Dynamically creating variables in Python is possible, but discouraged. The purpose of a variable is to have a convenient name for referencing something. A name the program knows. Dynamically creating variables kind of defeats the whole purpose of variables.
It can be useful to have a dictionary of functions. There are a lot of my first calculator programs that do this:
It can be useful to have a dictionary of functions. There are a lot of my first calculator programs that do this:
import operator operators = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv } while True: eq = input("Enter equation: ").split() if len(eq) != 3: break a, op, b = eq print(a, op, b, '=', operators[op](float(a), float(b)))Here I effectively give operator.add the name "+", but I did not create a "+" variable (it is impossible).