Open In App

Loops in Python - For, While and Nested Loops

Last Updated : 16 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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
For loop explanation

Example:

Python
n = 4
for i in range(0, n):
    print(i)

Output
0
1
2
3

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

Python
li = ["geeks", "for", "geeks"]
for i in li:
    print(i)
    
tup = ("geeks", "for", "geeks")
for i in tup:
    print(i)
    
s = "Geeks"
for i in s:
    print(i)
    
d = dict({'x':123, 'y':354})
for i in d:
    print("%s  %d" % (i, d[i]))
    
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
    print(i),

Output
geeks
for
geeks
geeks
for
geeks
G
e
e
k
s
x  123
y  354
1
2
3
4
5
6

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.

Python
li = ["geeks", "for", "geeks"]
for index in range(len(li)):
    print(li[index])

Output
geeks
for
geeks

Explanation: This code iterates through each element of the list using its index and prints each element one by one. The range(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. 

Python
li = ["geeks", "for", "geeks"]
for index in range(len(li)):
    print(li[index])
else:
    print("Inside Else Block")

Output
geeks
for
geeks
Inside 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
while loop explanation

All 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.

Python
cnt = 0
while (cnt < 3):
    cnt = cnt + 1
    print("Hello Geek")

Output
Hello Geek
Hello Geek
Hello 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.

Python
cnt = 0
while (cnt < 3):
    cnt = cnt + 1
    print("Hello Geek")
else:
    print("In Else Block")

Output
Hello Geek
Hello Geek
Hello Geek
In 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.

Python
while (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 called nested 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-Loop
Nested for loop

The 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-Loop
Nested while loop

A 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.

Python
from __future__ import print_function
for i in range(1, 5):
    for j in range(i):
        print(i, end=' ')
    print()

Output
1 
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

The continue statement in Python returns the control to the beginning of the loop.

Example:

Python
for letter in 'geeksforgeeks':
    if letter == 'e' or letter == 's':
        continue
    print('Current Letter :', letter)

Output
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current 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

The break statement in Python brings control out of the loop.

Example:

Python
for letter in 'geeksforgeeks':
    if letter == 'e' or letter == 's':
        break

print('Current Letter :', letter)

Output
Current Letter : e

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 use pass statement in Python to write empty loops. Pass is also used for empty control statements, functions and classes.

Example:

Python
for letter in 'geeksforgeeks':
    pass
print('Last Letter :', letter)

Output
Last Letter : s

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.

Python
fruits = ["apple", "orange", "kiwi"]

for fruit in fruits:

    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.

Python
fruits = ["apple", "orange", "kiwi"]
iter_obj = iter(fruits)
while True:
    try:
        fruit = next(iter_obj)
        print(fruit)
    except StopIteration:
        break

Output
apple
orange
kiwi

We can see that under the hood we are calling iter() and next() method. 

Quiz:


For loops in Python
Visit Course explore course icon
Video Thumbnail

For loops in Python

Video Thumbnail

While Loops in Python

Video Thumbnail

Nested Loops in python

Video Thumbnail

Loops In Python

Next Article
Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy