Loops
In short: A control structure that repeatedly executes a code block, as long as (or until) a specific condition is met — the basis for not having to write out repetitive tasks manually several times.
In more detail: Almost every language knows several loop types: pre-test (the condition is checked before every iteration, e.g. while), post-test (the condition is only checked after the first iteration, e.g. do...while), and counter-controlled loops (for). Which variant makes sense depends on whether the number of iterations is known in advance and whether the code block has to run at least once.
In Depth
Without loops, repeating code would have to be written out individually for every repetition — impractical for ten repetitions, simply impossible for ten thousand or a number unknown in advance:
# Without a loop (impractical):
print(1)
print(2)
print(3)
# ... x1000
# With a loop:
for i from 1 to 1000:
print(i)Within a loop, two special jump statements control the flow: break immediately leaves the loop entirely, regardless of whether the condition would still be met — useful, for example, when you’ve found a sought element and don’t need to keep searching. continue only skips the rest of the CURRENT iteration and moves directly on to the next one.
for element in list:
if element == target:
break # immediately exit the loop entirely
if element < 0:
continue # skip this iteration, continue
process(element)A common, serious mistake is the infinite loop: the exit condition is never met, because the relevant variable never changes in the right direction within the loop (e.g. a forgotten counter increment) — the program then apparently “hangs”, until it’s manually terminated or killed by the operating system. Deliberate infinite loops (while (true)) are nonetheless a legitimate pattern, e.g. for server main loops, as long as they have an internal break exit for the regular exit case.
See also: For Loop, While Loop, Pre-Test Loop, Post-Test Loop