0
votes

I have a set of variables: x1, x2, x3, x4, x5.

x1 = 10
x2 = 20
x3 = 30
x4 = 40
x5 = 50
number=1
for looper in range(0,4):
    xnumber = xnumber + 10
    number = number + 1

To get: x1 = 20, x2 = 30, etc. Because I got:

"'xnumber' is not defined"

How can I fix this?

4

4 Answers

3
votes

Use an array instead, defining x[0] ... x[4] and replacing xnumber with x[number]. Also, you can do without defining number and use the loop index:

x = range(5)
x[0] = 10
x[1] = 2
x[2] = 30
x[3] = 40
x[4] = 50
for i in range(0,5):
    x[i] = x[i] + 10
3
votes

Better use a list for this:

x = [10, 2, 30, 40, 50]
for index, value in enumerate(x):
    x[index] = value + 10

or a dict, if you want some 'names' for your values:

x = {'x1': 10, 'x2': 2, 'x3': 30, 'x4': 40, 'x5': 50}
for key, value in x.items():
    x[key] = value + 10

or a class:

class x:
    x1 = 10
    x2 = 2
    x3 = 30
    x4 = 40
    x5 = 50

for index in range(1, 6):
    attr_name = 'x%d' % index
    setattr(x, attr_name, getattr(x, attr_name) + 10)
0
votes

Integers aren't mutable. The only way to get what you want is to reassign each variable to a new integer, and you must do that individually to each variable - there's no way to create a loop to do it.

As an example of what I mean, here's what you could do if the values were mutable. I've changed each variable to contain a list instead of an int.

x1=[10]
x2=[20]
x3=[30]
x4=[40]
x5=[50]
vars = [x1, x2, x3, x4, x5]
for looper in range(0,4):
    vars[looper][0] = vars[looper][0] + 10
print x1,x2,x3,x4,x5
[20] [30] [40] [50] [50]

Notice that looper only goes up to 3 so it misses x5.

0
votes

Use a dictionary.

>>> d = {'x1':10,'x2':20,'x3':30,'x4':40,'x5':50}
>>> for key in d:
...   d[key] = d[key] + 10
>>> for key in sorted(d):
...   print key, '=', d[key]
...
x1 = 20
x2 = 30
x3 = 40
x4 = 50
x5 = 60