Search code examples
theory

Variable declaration from the value of a different variable


This isn't really specific to one language, it's just something I'm very confused about. I was wondering if you can declare a variable using the value from a different variable. ex:

 int a = 2;
 int ba = 3;
 //except instead of ba its b with the value of a so it would be b2=3;

I feel like I've done this before, but I can't for the life of me remember how it was done, or if I had ever done it in the first place. I apologize if this isn't in the correct category, I can't make my own, and I don't really know what would be a better place for it.


Solution

  • In python, exec() accepts and executes strings that contain valid Python expressions. You should try this

    >>> a = 2 
    >>> exec('b' + str(a) + ' = ' + str(3))
    >>> b2
    

    The output will be 3

    3