-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
  • 19,640
  • 49
  • 136
  • 276

2 Answers2

2
for _ in range(25):
    index = int(random.uniform(0, len(characters)))
    code += characters[index]
return code
Nouman
  • 6,947
  • 7
  • 32
  • 60
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
  • 88,713
  • 10
  • 131
  • 172