For Loop

In Python, a for loop is used to iterate over a sequence of items, such as a list, tuple, string, or other inerrable objects. The loop iterates over each item in the sequence and executes a block of code for each item.

Note: In Python, we do not need counter variable in for-loop. The for loop starts and iterates over the sequence. It executes the block of for-loop for every single item for one time.

The range function in for loop

In Python, the range() function is employed to create a numerical sequence within a defined range. This function yields an inerrable entity that signifies the progression of numbers. It is frequently employed in conjunction with loops to facilitate iteration over a designated range of numerical values.

We can specify not only the start and end of range function but also the gaps/jumps.

Else Statement in for loop

We can also use else statement in for-loop. The code in else statement will be executed when the condition becomes false.

Note: The code in the else block is not executed if the loop is stopped by a break statement.

Nested Loops

In Python, a nested loop is when one loop is contained within another loop. This structure enables the execution of a group of statements repeatedly, with each repetition of the outer loop's iteration. Nested loops are particularly beneficial for tasks that involve performing repetitive actions on various levels or dimensions of data.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

What will be the output?

15 XP~4 min
for(i = 0 i < 3 i++) :
    print(i)
Exercise 2 of 2Easy

To exit a loop immediately, we use the ___ statement.

10 XP~2 min