-1

I tried to make an x1, x2, x3 etc', but I dont know how... I tried to make this code as a while:

x1=random.choice(string.letters)
x2=random.choice(string.letters)
x3=random.choice(string.letters)
x4=random.choice(string.letters)
x5=random.choice(string.letters)
x6=random.choice(string.letters)
x7=random.choice(string.letters)
x8=random.choice(string.letters)
x9=random.choice(string.letters)
x10=random.choice(string.letters)

but when I tried to write it as a while loop:

i=1 #Counter

#Letter Creation
while i<=10:
    x(i) = random.choice(letterschoice)

but there is an error. How do I fix the x(i) and make it x1, x2, x3 etc'?

Maor Gordon
  • 67
  • 1
  • 1
  • 6

2 Answers2

2

Instead of having ten different variables, it would be much easier to use a list:

x = []

for i in range(0, 10):
    x.append(random.choice(letterschoice))

You can then use the [] operator to access specific elements of x. Just note that it uses a zero-based index (i.e., the first element is x[0], the second is x[1], etc.).

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • really good answer, but it does not exactly answer the question. – Derlin Apr 12 '16 at 08:25
  • 1
    @Derlin: The question is an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem); this answer is a much better solution for the questioner's underlying goal than dynamically creating numbered variables. It's just that before people are familiar with lists and dicts, they think of the problem in terms of "how do I create numbered variables" or "how do I create variables from strings" instead of "how do I store a sequence of values", leading to questions they can't realize are poorly posed. – user2357112 Apr 12 '16 at 08:31
  • I perfectly agree. You are right, but I also thought of other people needing to actually use variables. Anyway, your answer is perfectly fine. – Derlin Apr 12 '16 at 08:37
1

One possibility is to use exec, even if it is really bad in terms of security:

>>> exec( 'x1 = ' + str(2))
>>> x1
2

In a loop:

 for i in range(0,10):
     cmd =  "x%d = %d" % (i,random.choice(letterschoice))
     exec(cmd)

A better way is to use the globals or the locals() magic:

>>> globals()["x1"] = 3
>>> x1
3

In a loop:

for i in range(0, 10):
    globals()["x" + str(i)] = random.choice(letterschoice)

If your variable belongs to an object instead, use setattr(self, "varname", value).


Of course, in your example it would be more suitable to use a list x[]. You then use it like x[1], etc.

You could also use a dictionary, if the string 'x1' etc are important. In python, dict look like: {'x1': val, 'x2', val2} etc. You can use it with myDict["x1"] for example.

Derlin
  • 9,572
  • 2
  • 32
  • 53