2 ms·
> A while loop introduces unbounded computation. Then so does a for loop. There’s no difference in this regard between for and while loops: you can use both of
by chrismorgan 5y ago
> A while loop introduces unbounded computation.
Then so does a for loop. There’s no difference in this regard between for and while loops: you can use both of them to express both bounded and unbounded computations, and in each case you need to read and understand at least what comes before the colon to know which it is.
# Unbounded
while True:
pass
# Bounded
while False:
pass
# Unbounded
for i in itertools.count():
pass
# Bounded
for x in []:
pass
And you can’t just say “but with for loops you only need to worry about the iterator, whereas with while loops you’ll probably need to worry about statements inside the loop in addition to the loop condition”, as seen in this entirely realistic function that is unbounded if source == target (assuming a port of the DOM API, so child_nodes is a live collection):
def clone_children_to(source: Element, target: Element):
for node in source.child_nodes:
target.append_child(node.clone())
(I agree that for loops are generally preferable to while loops where feasible, but I object to the way you’ve expressed that paragraph, and the expressed reasoning underpinning the entire section is flawed, as priansh also points out.)