CODER KID
CODER KID

Reputation: 58

Changing multiple variables using other variables Python

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.

Upvotes: 0

Views: 49

Answers (2)

Kamil B
Kamil B

Reputation: 95

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

Upvotes: 1

HariUserX
HariUserX

Reputation: 1334

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

Upvotes: 0

Related Questions