Python For Loop

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 loops are loops supported by Python.

The for Loop in Python

The for loop is used to traverse a sequence object like List, Tuple, String, and Python’s other collection data types. In other programming languages, the for loop is used as just another type of while loop, but in Python, it is used to iterate over a sequence of objects.

Syntax

For target in objects statements

The loop above starts with the for keyword and ends with a semicolon, the loop variable target is assigned the first item of the object. Then the loop code is executed, then the second item is assigned, and the loop code is executed, and so in till the last item is assigned. 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 a 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, 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, the else block is not executed because the break statement was executed.

Following is the example of the for loop that finds whether a number is even or odd.

			

numbers = [20, 3, 69, 58, 63, 50]
for n in numbers:
	if n % 2 == 0:
		print(n, "is an even number.")
	else:
		print(n, "is an odd number.")

				

Output:

20 is an even number. 3 is an odd number. 69 is an odd number. 58 is an even number. 63 is an odd number. 50 is an even number.

Here is the example of the for loop finding out vowels in the series of alphabets.

			

for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": 
	if letter in "AEIOU": 
		print(letter, "is a vowel") 
	else: 
		print(letter, "is a consonant")