In this article, we will know all about the For loops used in Python with suitable examples. So, before coming to the topic you should know that we use for loops in order to introduce any iteration in our code. The following are the contents of this article:
- Introduction
- Loop through a string
- break statement
- continue statement
- range of function
- use of else
- nested for loops
- pass statement
Introduction
For loop allows the iteration in any list, set, tuple or dictionary. Like other object-oriented programming languages, we also use for loop in Python to show the iteration.
tuple1 = ("mango", "apple", "banana")
for x in tuple1:
print(x)
The above example is of a tuple
list1 = ["mango", "apple", "banana"]
for x in list1:
print(x)
This example is of a list
set1 = {"mango", "apple", "banana"}
for x in set1:
print(x)
This is a loop of a set
dict = {
"brand":"Realme",
"model":"X50 pro",
"year" :"2020"
};
for x in dict:
print(dict[x])
This example is of a dictionary
Loop through a String
The string contains characters in a sequence which can be iterable if we use for loops through this.
for i in "Python Tutorial":
print(i)
Output:
The break statement
In order to stop the loops before the entire iteration through each item, we use the break statement.
set1 = {"mango", "apple", "banana"}
for i in set1:
print(i)
if i == "mango":
break #returns mango
The continue statement
We use continue statement to exit the current iteration and go through the next iterations
set1 = {"mango", "apple", "banana", "lichi", "cucumber", "cherry"}
for i in set1:
if i == "banana":
continue
print(i)
The range function
We use range function to show any sequence starting from 0(by default) and the values all incremented by 1(by default).
for i in range(10):
print(i) #returns all the numbers starting from 0 to 9(10-1) increamented each time by 1
look the range it takes is from 0 to 9(or n-1)
Now if we mention the starting and ending index of the range we can write in this fashion:
for i in range(1,7):
print(i) #returns numbers from 1 to 6(7-1) incremented each time by 1
User can also set the increment value of the range
for i in range(2,10,2):
print(i) #returns 2 to 8 increamented by 2 each time
Else in For loop
After the execution of the for loop else is used to print any specific statement
for i in range(2,10,2):
print(i)
else:
print("We get numbers from 2 to 8 increamented each time by 2")
Nested loops
Nested loop refers to the loop inside a loop. There are inner loop and the outer loop. The concept this nested loop is that the inner loop will execute after each iteration of the outer loop.
for i in range(4):
for j in range(4):
print(i)
Output:
The pass statement
If we have a for loop without any statement we should give the pass statement otherwise it will show an error.
for i in range(1,6,2):
pass