Dynamic Variable Name

Let’s say I have set

q_variable = 0
a_variable = 0

def stats(choice):
choice + ‘_variable’ += 1

stats(‘q’)

Here after adding the choice + ‘_variable’ will become string.
How do we do change the q_variable or the a_variable depending on the choice we provide to the function?

you should remove the quotation marks because when you are adding a variable you shouldn’t add quotation marks because that forces it to become a string. also if you want this to be a:

_variable +=1

you should do this maybe:

q = 0
a = 0
q_and_a_variable = [a, q]

def stats(choice):
choice + q_and_a_variable += 1

stats(‘q’)
1 Like

Use a dictionary instead:

variable = {
    'q': 0,
    'a': 0
}

def stats(choice):
    variable[choice] += 1

stats('a')
4 Likes

Or an object if you are doing Object Oriented Programming. You can update an object’s attributes dynamically using getattr and setattr.

2 Likes