Python Forum
Results name is a variable itself
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Results name is a variable itself
#3
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:
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).
Reply


Messages In This Thread
Results name is a variable itself - by paul18fr - Mar-25-2022, 08:32 AM
RE: Results name is a variable itself - by ibreeden - Mar-25-2022, 09:08 AM
RE: Results name is a variable itself - by deanhystad - Mar-25-2022, 07:42 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Search Results Web results Printing the number of days in a given month and year afefDXCTN 1 2,268 Aug-21-2020, 12:20 PM
Last Post: DeaD_EyE
  How to append one function1 results to function2 results SriRajesh 5 3,224 Jan-02-2020, 12:11 PM
Last Post: Killertjuh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020