-2

I have googled on how to write a fixed length loop in Python but haven't found anything, so I ask here:

    for i in range(0, 25):
        index = int(random.uniform(0, len(characters)))
        code += characters[index]
    return code

As you see I don't need i. How can I rewrite this to be a fixed length loop where I don't have to define i?

user1283776
  • 16,122
  • 38
  • 122
  • 229

2 Answers2

2
for _ in range(25):
    index = int(random.uniform(0, len(characters)))
    code += characters[index]
return code
Black Thunder
  • 6,215
  • 5
  • 27
  • 56
2

Here you go, no unnecessary variable required:

it = iter(range(25))
while True:
    try:
        next(it)
    except StopIteration:
        break
    # do stuff
    pass

Of course, that introduces an ugly necessary variable, and basically re-implements the python iterator-based for-loop using a while-loop, but that is an option.

Most people would go for the idiomatic for-loop, and maybe use the conventional throw-away variable, the underscore:

for _ in range(25):
    # do stuff
    pass
juanpa.arrivillaga
  • 77,035
  • 9
  • 115
  • 152