Reputation:
I have a bit of question with python.
I have a piece of code
screen.blit(badninja1,(badninja1px ,badninja1py))
screen.blit(badninja2,(badninja2px ,badninja2py))
screen.blit(badninja3,(badninja3px ,badninja3py))
I know it repeats 3 time and I want to do some refactoring.
That is a piece of python code what it does was draw badninja1 at location badninja1px and badninja1py etc. bandninja1, badninja1px, badninja1py and other are variable names.
I wanted to put this code in a for loop
for x in range(1, 4):
#add number 1, 2, 3 to the variable name.
I tried to do that and realized that I can combine string easily in python:
"Dec "+str(25)+"th".
However, changing variable name is a bit tricky.
Can anybody give ma a hint thanks!!
Upvotes: 0
Views: 163
Reputation: 3857
Instead of calling the variables explicitly, put them in the list then iterate over this one:
my_list = [(badninja1, badninja1px ,badninja1py),
(badninja2, badninja2px ,badninja2py),
(badninja3, badninja3px ,badninja3py)]
for item in my_list:
screen.blit(item[0], (item[1], item[2]))
Upvotes: 0
Reputation: 1125058
You'd normally keep those values in lists or dictionaries instead:
badninjas = [badninja1, badninja2, badninja3]
and keep information like their location with the badninja
objects:
for ninja in badninjas:
screen.blit(ninja, (ninja.px, ninja.py))
You can look up variables dynamically, using either the globals()
or locals()
results (both return a mapping) but generally speaking you should avoid such behaviour. It certainly shouldn't be needed here.
Upvotes: 5
Reputation: 336478
The solution is to not use numbers in a variable name. Use a list instead:
badninja = [firstitem, seconditem, thirditem, ...]
Now you can pass badninja[0]
to your function to specify the first item etc.
Upvotes: 3