In Python, a for loop is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code repeatedly for each item in that sequence.
Syntax:
Examples:
1. Iterating over a list:
Output:
2. Iterating over a string:
Output:
3. Using range()
function:
The range()
function is commonly used with for
loops to generate a sequence of numbers.
Output:
You can also specify a start, stop, and step in range()
:
Output:
4. Iterating over a dictionary:
Output:
Nested For Loops:
A nested for loop is a loop inside another loop. This is often used to work with multi-dimensional data structures (like lists of lists).
Output:
break
and continue
in for loops:
break
: Exits the loop entirely.continue
: Skips the current iteration and moves to the next iteration.
Output:
Output:
For loops are very versatile and can be used for many tasks such as traversing collections, generating sequences, and performing repeated actions.