0

I am currently writing my first script in python and have functions that are all similar, except for the fact that one number in each variables name changes.

For example like this:

def Function1(): 
    global Var1 
    Var1 = A1 
    global Var2 
    Var2 = B1

def Function2(): 
    global Var1 
    Var1 = A2 
    global Var2 
    Var2 = B2

The variables Ax, Bx and so on are read from a file. Then, if I click a tkinter-Button, one of these functions is activated and the global variables Var1 and Var2 are set to either A1 and B1 or A2 and B2 and so on...

Since this is just copy and pasting the functions and then manually changing the number in the variable name that is read from the file, I thought there has to be a way to make this easier. Something like this:

def Function1():
    FUNCTIONNUMBER = 1
    global Var1 
    Var1 = ("A" + FUNCTIONNUMBER) 
    global Var2 
    Var2 = ("B" + FUNCTIONNUMEBR)

In other words, something that makes it possible to set up a variable name from a constant part ("A") and a changing part ("1" or "2" or "3"...)

I´ve already searched for this question, but didn´t find anything that helps me with my specific case, since I don´t want to create variables out of nowhere or I don´t want to write all the variable names in a dictionary. I just want to make python think it reads a variable name that consists of different parts.

Thank you in advance!

Diego Mora Cespedes
  • 3,605
  • 5
  • 26
  • 33
J.Doe
  • 1
  • 3
    Just use lists or dicts of `A`'s and `B`'s instead of constructing variable names. You _can_ do it, but you shouldn't. – Lev Levitsky Jul 15 '17 at 22:59
  • I believe what you are trying to describe is, if I remember right, is a thing as if it was it would be a major vulnerability. – Max Jul 15 '17 at 23:34

1 Answers1

0

I think what you're looking for is a list. let me show you and example

some_list = ["hey", "hows", "it", "going"]
print(some_list[0])
print(some_list[2])

This output would be:

hey
it

a list is just that, a list of numbers/strings/function/other lists, and you access them by specifying which position in the list you want (starting at 0)

Mauricio
  • 419
  • 4
  • 14