0

My question is about Python variables. I have a bunch of variables such as p1, p2 and p3. If I wanted to make a loop that let me change all of them at once, how would I do that? Here is what I got so far.

p1 = 0
p2 = 0
p3 = 0
p4 = 0
p5 = 0
p6 = 0
p7 = 0
p8 = 0
p9 = 0
p10 = 0



x = 10

while(x < 0):
    p+str(x) = p+str(x) + 1
    x - 1

This code should change 10 variables called p1, p2, p3 (ect) by 1 each.

5
  • 1
    One common pattern is to instead have a list p, instead of individual variables, and store your values such that p2 == p[2]. Then just iterate over that list. Commented Jul 20, 2018 at 18:05
  • In this case, I can only use variables. Unfortunately, I cannot use lists, arrays, objects or dictionaries. Commented Jul 20, 2018 at 18:20
  • 1
    @CODERKID why ? Commented Jul 20, 2018 at 18:20
  • @brunodesthuilliers Because it is for pygame, but I didnt want to involve Pygame because then nobody would look at this question. Commented Jul 20, 2018 at 18:21
  • And how does pygame prevents you from using a list ? Also, if you hope to get any serious answer (not hacks from copy-paste 'coders') you'd rather explain your real problem (search for "xy problem" if you want to know why). Commented Jul 20, 2018 at 18:24

2 Answers 2

1

You cannot add a number to a variable like that, instead you might want to use a Object, array or a dictionary. What you are trying to do, can be done in a dictionary really easily. The code below shows how you can implement your code with dictionary.

dictionary = {} # it can hold P1 P2 p3...
x = 10
while(x < 0):
    dictionary["p" + str(x)] = dictionary["p" + str(x)] + 1
    x - 1

You may want to research more about this subject as this is just a quick example of how to use a dictionary in python

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

Comments

0
>>> p1=0
>>> p2=0
>>> p3=0
>>> x=3
>>> while(x>0):
        exec("%s%d += 1"%("p",x))
        x = x -1

>>> p1
1
>>> p2
1
>>> p3
1

Although this does the job. Don't follow this approach(really bad way), instead look for alternative like using lists or dicts.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.