0

I'm learning programming with Python, and I need a function where I can send different variables to modify them, but if the variable doesn't exist, it creates one with a defined value.

Lets say I have...:

x = 83
y = 91

... And I need a function that modifies the existing variables, but if I send a variable that is not defined, then it creates it. Say I need that any variable created starts at 60. So I send the Z value to my function, and since it isn't defined, it defines z = 60.

My problem is I don't even know how to write said function. Is it even possible? Or do i need to have z = 0 as a placeholder, check if it's equal to 0, and then modify it? I don't want to have variables that may not be used occupying space. I'm using Python 3.

  • 1
    you don't want to do that, not in the global namespace at least, use a dictionary for this with string keys and integer values – Matiiss Dec 02 '21 at 16:49
  • This sounds like [module `__getattr__`](https://www.python.org/dev/peps/pep-0562/), where the name of the attribute is passed as an argument. – a_guest Dec 02 '21 at 16:50
  • 2
    Every beginner wants to do this at some point, then they fail, at some point they realize that using a container (dictionary) is the key (pun intended) – mozway Dec 02 '21 at 16:50
  • If you just want to change arbitrary variables, the `=` syntax does exactly that. – luther Dec 02 '21 at 16:54
  • Use a `defaultdict(int)`, or a `Counter`. You can wrap it in a function if you want, but that's not necessary. – Samwise Dec 02 '21 at 16:55

0 Answers0