Reputation: 2451
I have a use case where I need to repeat some block of code:
I am wondering, is there some Python built-in way to:
while
loopfor
loopNote: I know I can use an if
statement (depending on if upper limit is present), and switch between a for
or while
loop. I am trying to not have the code block repeated twice, or it broken out into another function.
Current Implementation
I wrote the below flawed (see below) for_while_hybrid.py
using Python 3.8.2.
from typing import Iterator
def iter_for_while(num_yield: int = None) -> Iterator[int]:
"""Generate an incrementing counter.
This enables one to make a for loop or a while loop, depending on args.
Args:
num_yield: Number of times to yield.
If left as None, the generator makes a while loop
If an integer, the generator makes a for loop
"""
counter = 0
condition = True if num_yield is None else counter < num_yield
while condition:
yield counter
counter += 1
if num_yield is not None:
condition = counter < num_yield
upper_limit = 5
for _ in iter_for_while(upper_limit):
print("Some code block") # Run 5 times
for _ in iter_for_while():
print("Some code block") # Run infinitely
This implementation works.
The downside is, if run for a very long time, I am worried the counter
will take up lots of memory, or will eventually max out. My computer is 64-bit, so sys.maxsize = 2 ** 63 - 1 = 9,223,372,036,854,775,807
.
Upvotes: 0
Views: 188
Reputation: 531718
Just use count
or range
, depending on the upper bound:
from itertools import count
def iter_for_while(bound=None):
return count() if bound is None else range(bound)
Upvotes: 6
Reputation: 503
use a while loop but you can say while X < Y: do something and then X += 1 this means you can control how many times it repeats with X or if you want it indefinitely then don't say X + 1
Upvotes: 1