Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). In this article, we will look at Python loops and understand their working with the help of examples.
For Loop in Python
For loops is used to iterate over a sequence such as a list, tuple, string or range. It allow to execute a block of code repeatedly, once for each item in the sequence.
Syntax:
for iterator_var in sequence:
statements(s)
For loop explanationExample:
Pythonn=4foriinrange(0,n):print(i)
Explanation: This code prints the numbers from 0 to 3 (inclusive) using a for loop that iterates over a range from 0 to n-1 (where n = 4).
Example:
Iterating Over List, Tuple, String and Dictionary Using for Loops in Python
Pythonli=["geeks","for","geeks"]foriinli:print(i)tup=("geeks","for","geeks")foriintup:print(i)s="Geeks"foriins:print(i)d=dict({'x':123,'y':354})foriind:print("%s%d"%(i,d[i]))set1={1,2,3,4,5,6}foriinset1:print(i),
OutputgeeksforgeeksgeeksforgeeksGeeksx 123y 354123456
Iterating by the Index of Sequences
We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the length of the list and then iterate over the sequence within the range of this length.
Pythonli=["geeks","for","geeks"]forindexinrange(len(li)):print(li[index])
Explanation:This code iterates through each element of the list using its index and prints each element one by one. Therange(len(list)) generates indices from 0 to the length of the list minus 1.
Using else Statement with for Loop in Python
We can also combine else statement with for loop like in while loop. But as there is no condition in for loop based on which the execution will terminate so the else block will be executed immediately after for block finishes execution.
Pythonli=["geeks","for","geeks"]forindexinrange(len(li)):print(li[index])else:print("Inside Else Block")
OutputgeeksforgeeksInside Else Block
Explanation:The code iterates through the list and prints each element. After the loop ends it prints "Inside Else Block" as the else block executes when the loop completes without a break.
While Loop in Python
In Python, a while loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.
Syntax:
while expression:
statement(s)
while loop explanationAll the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.
Example:
This example demonstrates a basic while loop in Python. The loop runs as long as the condition cnt < 3 is true. It increments the counter by 1 on each iteration and prints "Hello Geek" three times.
Pythoncnt=0while(cnt<3):cnt=cnt+1print("Hello Geek")
OutputHello GeekHello GeekHello Geek
Using else statement with While Loop in Python
Else clause is only executed when our while condition becomes false. If we break out of the loop or if an exception is raised then it won't be executed.
Syntax of While Loop with else statement:
while condition:
# execute these statements
else:
# execute these statements
Example:
The code prints "Hello Geek" three times using a 'while' loop and then after the loop it prints "In Else Block" because there is an "else" block associated with the 'while' loop.
Pythoncnt=0while(cnt<3):cnt=cnt+1print("Hello Geek")else:print("In Else Block")
OutputHello GeekHello GeekHello GeekIn Else Block
Infinite While Loop in Python
If we want a block of code to execute infinite number of times then we can use the while loop in Python to do so.
The code given below uses a 'while' loop with the condition "True", which means that the loop will run infinitely until we break out of it using "break" keyword or some other logic.
Pythonwhile(True):print("Hello Geek")
Note: It is suggested not to use this type of loop as it is a never-ending infinite loop where the condition is always true and we have to forcefully terminate the compiler.
Nested Loops in Python
Python programming language allows to use one loop inside another loop which is callednested loop. Following section shows few examples to illustrate the concept.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
Nested for loopThe syntax for a nested while loop statement in the Python programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
Nested while loopA final note on loop nesting is that we can put any type of loop inside of any other type of loops in Python. For example, a for loop can be inside a while loop or vice versa.
Pythonfrom__future__importprint_functionforiinrange(1,5):forjinrange(i):print(i,end=' ')print()
Output1 2 2 3 3 3 4 4 4 4
Explanation:In the above code we use nested loops to print the value of i multiple times in each row, where the number of times it prints i increases with each iteration of the outer loop. The print() function prints the value of i and moves to the next line after each row.
Loop Control Statements
Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.
Continue Statement
Thecontinue statement in Python returns the control to the beginning of the loop.
Example:
Pythonforletterin'geeksforgeeks':ifletter=='e'orletter=='s':continueprint('Current Letter :',letter)
OutputCurrent Letter : gCurrent Letter : kCurrent Letter : fCurrent Letter : oCurrent Letter : rCurrent Letter : gCurrent Letter : k
Explanation:The continue statement is used to skip the current iteration of a loop and move to the next iteration. It is useful when we want to bypass certain conditions without terminating the loop.
Break Statement
Thebreak statement in Python brings control out of the loop.
Example:
Pythonforletterin'geeksforgeeks':ifletter=='e'orletter=='s':breakprint('Current Letter :',letter)
Explanation:break statement is used to exit the loop prematurely when a specified condition is met. In this example, the loop breaks when the letter is either 'e' or 's', stopping further iteration.
Pass Statement
We usepass statement in Python to write empty loops. Pass is also used for empty control statements, functions and classes.
Example:
Pythonforletterin'geeksforgeeks':passprint('Last Letter :',letter)
Explanation:In this example, the loop iterates over each letter in 'geeksforgeeks' but doesn't perform any operation, and after the loop finishes, the last letter ('s') is printed.
How for loop works internally in Python?
Before proceeding to this section, we should have a prior understanding of Python Iterators.
Firstly, lets see how a simple for loops in Python looks like.
Example 1:
This Python code iterates through a list called fruits, containing "apple", "orange" and "kiwi." It prints each fruit name on a separate line, displaying them in the order they appear in the list.
Pythonfruits=["apple","orange","kiwi"]forfruitinfruits:print(fruit)
This code iterates over each item in the fruits list and prints the item (fruit) on each iteration and the output will display each fruit on a new line.
Example 2:
This Python code manually iterates through a list of fruits using an iterator. It prints each fruit's name one by one and stops when there are no more items in the list.
Pythonfruits=["apple","orange","kiwi"]iter_obj=iter(fruits)whileTrue:try:fruit=next(iter_obj)print(fruit)exceptStopIteration:break
We can see that under the hood we are calling iter() and next() method.
Quiz:
Related Posts:
Recommended Problems:

For loops in Python

While Loops in Python

Nested Loops in python

Loops In Python