Imagine you need to send a thank-you text message to a thousand customers. Writing a thousand lines of code is clearly not the right way. A loop lets you write the instruction once and say "repeat this for every customer".

Common types#

  • for: use it when you know how many times to repeat, or which collection to go through.
  • while: keep going as long as a condition holds.

Example#

PYTHON
for name in ["Ali", "Sara", "Reza"]:
    print("Hello", name)

This loop runs three times, once for each name.

Where it is used#

Showing a store's product list, reading the rows of a spreadsheet, checking all comments to find spam, and hundreds of other tasks are done with loops.

Beware of infinite loops#

If the stopping condition is never met, the loop continues forever and the program freezes or ties up the processor. For example, in a while loop, if you forget to increase the counter, it never ends.

A performance note#

A loop inside a loop can become very slow with large amounts of data. If your program suddenly slows down as data grows, nested loops are the first place to check.