For loop in python:
For loop in python is used to traverse through a sequence of lists, tuples, or any iterable objects.
For loop in python works quite similar to an iterator that is found in other programming languages like Java.., Where we usually do not use indexes to get items from the iterable object.
In each iteration, elm takes the item from the sequence/iterable_object
For example, if the loop is running on a list = [10,22,31], in the first iteration elm will have 10, and in the 2nd iteration, elm will have 22 and in the last iteration elm will have 31
Loop will run till the last element in the sequence.
Flow chart for better understanding:
Example 1 :
Program to get even numbers from the list using for loop
myList = [3,6,2,9,24] for elm in myList: #check even or not if(elm%2 == 0): print(elm)
How does the above code work?
For loop on range() function
Find the sum of numbers between 2 given numbers
n1 = 2 n2 = 5 sum = 0 for elm in range(n1, n2+1): sum += elm print(sum)
Explanation: range() function will generate a sequence of numbers between 2 numbers (2nd number not included), so in our case range() generates a sequence of numbers from 2 to 5 i.e [2,3,4,5], and these numbers are added to the sum variable one by one in every iteration.
For loop with else:
For loop with else is same as For loop but else part is added to it, This else part is executed when the loop runs till the last element without terminating in between the iterations. And the else part is not executed when the loop is terminated in between the iterations with the break keyword.
For loop with else ( Without break)
myList = [1,3,4] for elm in myList: print(elm) else: print("Else part executed..!")
Else part executed..!
Explanation: The loop is not terminated by “break”, and all the elements in the list have been processed, So the else part is also executed.
For loop with else ( With break)
myList = [1,3,4] for elm in myList: if elm == 3: break print(elm) else: print("Else part executed..!")
Explanation: Since the loop is terminated by “break”, so the else part will not be executed.
Special thanks to Sai bargav Nellepalli for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article