Python Loops

What are Loops in Python?

Loops in Python allow the programmer to execute a piece of code a certain number of times depending on a given condition. If the condition becomes False, the execution of the loop is terminated. There are two types of Loops in Python, For Loop and While Loop. We can use the break statement to end the execution of the loop early.

These Python loops are further discussed below.

The for Loop in Python

The for loop is used to traverse a sequence object like List, Tuple, String, etc. We specify a target and the sequence to be traversed to the for loop. It works by assigning the elements in the sequence to target one by one and executing the loop body for each. We can use the target to refer to the current element in the sequence inside the loop body.

			

fruits = ["Apple", "Mango", "Banana", "Watermelon"]
for fruit in fruits:
	print(fruit)

				

Output:

Apple Mango Banana Watermelon

We can also define an else block with the for loop. This else block is executed only when all the elements inside the sequence have been traversed.

			

fruits = ["Apple", "Mango", "Banana", "Watermelon"]
for fruit in fruits:
	print(fruit)
else:
	print("All the fruits have been traversed")

				

Output:

Apple Mango Banana Watermelon All the fruits have been traversed

Note that if the break statement is executed inside the loop, then the else block is not executed. It is only executed when all the elements in the sequence have been traversed.

			

fruits = ["Apple", "Mango", "Banana", "Watermelon"]
for fruit in fruits:
	print(fruit)
if(fruit==”Banana”):
	break
else:
	print("All the fruits have been traversed")

				

Output:

Apple Mango Banana

As you can see here, the else block is not executed because the break statement was executed.