0

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!!

2
  • Messing with variable names is not a good practice (in any language): try a different approach to the problem Commented Nov 4, 2013 at 10:43
  • thanks! I had limited time to get a game working. It was not the best practice, I know. Sorry Commented Nov 4, 2013 at 10:56

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

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]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.