Python For Loops

A for loop allows you to iterate over a sequence of elements, such as a list, tuple, string, or range. It is useful for performing repetitive tasks on each item in a sequence.

Basic For Loop

The basic syntax of a for loop is as follows:

The for loop iterates over each item in the sequence, executing the indented block of code for each item.

Tutorials dojo strip
Python

In this example, the loop prints each fruit in the fruits list.

Python

Looping Through a String

You can use a for loop to iterate over each character in a string. The loop iterates over each character in the string and executes the code block for each character.

Python

Looping Through a Range

The range() function creates a sequence of numbers from 0 up to (but not including) the specified end value, which can be used to control the number of times a loop executes. In this example, the loop prints numbers from 0 to 4.

Python

Looping with an Else Clause

You can include an else clause with a for loop. The else block will be executed after the loop finishes iterating over all items in the sequence. The else block runs after the loop completes normally.

Python

Breaking out of a For Loop

You can use the break statement to exit a for loop prematurely, even if there are more items to iterate over.

In this example, the loop prints numbers from 0 to 4 and then exits when i is equal to 5. The break statement immediately terminates the loop.

Python

Skipping Iterations in a For Loop

The continue statement skips the current iteration and moves to the next iteration of the loop.

In this example, the loop prints only odd numbers from 0 to 9. The continue statement allows you to skip specific iterations based on a condition.

Python

Nested For Loops

You can nest for loops within each other to iterate over multi-dimensional data structures.

This example prints each item in a 2D list (matrix) in a structured format. Nested for loops allow you to iterate over each item in a multi-dimensional sequence.

Python

Python For Loops Example Code

This program uses for loops to iterate over lists, strings, ranges, and demonstrates breaking out of loops, skipping iterations, and nesting loops.

Python

Python Labs

Tutorials dojo strip