for Loop

Python’s ‘for loop’ is a control flow statement that allows code to be executed repeatedly. This is ideal when you want to run a block of code a certain number of times, or for each item in a sequence (like a list or a string).

Basic Structure of for Loop

The basic structure of a ‘for loop’ in Python is as follows:

1for variable in sequence:
2    # code to be executed for each item

Here, ‘sequence’ can be any iterable object in Python, and ‘variable’ is a temporary variable that takes the value of each item in the sequence during each iteration of the loop.

Example of for Loop

Here’s an example of a ‘for loop’ that prints each character of a string:

1for character in 'Hello, World!':
2    print(character)

This loop will iterate over the string ‘Hello, World!’, and for each iteration, it will print the current character.

Using range() Function with for Loop

In many cases, you may want to iterate over a sequence of numbers. The range() function comes in handy in such scenarios. Here’s an example:

1for i in range(5):
2    print(i)

This code will print numbers from 0 to 4. The range() function generates a sequence of numbers starting from 0 and ending at one less than the specified number.

for Loop with else Statement

Just like ‘if’ and ‘while’, ‘for loop’ in Python also supports an ’else’ clause that is executed after the loop finishes its execution, but it won’t execute if the loop is terminated with a ‘break’ statement.

1for i in range(5):
2    print(i)
4    print("Loop has ended")

In this script, after printing numbers from 0 to 4, the script will print ‘Loop has ended’.


The ‘for loop’ in Python is much more versatile than in many other programming languages because it can iterate not only over a range of numbers but also over any iterable object (like lists, strings, dictionaries, sets, or tuples).