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

The most commonly used loop in Python. A for loop 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.

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 True. The loop continues until the condition becomes False.

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.

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)

Tutorial

Python "for" Loops (Definite Iteration)

In this introductory tutorial, you'll learn all about how to perform definite iteration with Python for loops. You’ll see how other programming languages implement definite iteration, learn about iterables and iterators, and tie it all together to learn about Python’s for loop.

basics python

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


By Dan Bader • Updated Jan. 8, 2025