Skip to content

loop

A loop is a programming construct that allows you to repeat a block of code multiple times. In Python, loops are essential for automating repetitive tasks, processing collections of data, and creating efficient, concise code. Rather than writing the same instructions over and over, loops let you write them once and execute them repeatedly based on specific conditions.

for Loop

A for loop is the most commonly used loop in Python. It iterates over a sequence (like a list, tuple, or string) or other iterable objects. It executes a block of code once for each item in the sequence.

Language: Python
for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

while Loop

A while loop repeatedly executes a block of code as long as a given condition remains truthy. The loop stops once the condition becomes falsy, which may happen on the very first check.

Language: Python
count = 0
while count < 3:
    print(count)
    count += 1

Nested Loops

Loops can be placed inside other loops. The inner loop completes all its iterations for each single iteration of the outer loop.

Language: Python
for i in range(2):
    for j in range(2):
        print(f"i: {i}, j: {j}")

Loop Control Statements

  • break: Exits the loop completely
  • continue: Skips the rest of the current iteration and moves to the next one
  • else: Executes when the loop completes normally (not when broken by break)
Python "while" Loops (Indefinite Iteration)

Course

Mastering While Loops

Master indefinite iteration using the Python "while" loop. You’ll be able to construct basic and complex while loops, interrupt loop execution with break and continue, use the else clause with a while loop, and deal with infinite loops.

basics python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Dan Bader • Updated Oct. 13, 2026 • Reviewed by Leodanis Pozo Ramos