A loop repeats a block of code multiple times. Instead of writing the same code over and over, you write it once and tell the program how many times — or under what condition — to repeat it.
Without loops, a program runs each line exactly once. With loops, it can repeat work automatically.
Types of Loops#
While Loop#
Repeats as long as a condition is true. Used when you don’t know in advance how many times to repeat.
See While Loop for a full explanation and examples.
For Loop#
Repeats a set number of times. Used when you know exactly how many iterations you need.
Foreach Loop#
Repeats once for each item in a collection. Used when iterating over lists, arrays, or other sequences.