Table of contents
1.
Introduction
1.1.
Why are Loops Used?
2.
Types Of Loops In Python
2.1.
WHILE LOOP
2.1.1.
Flow Chart of While Loop
2.2.
Python
2.2.1.
Single Statement While Loop
2.2.2.
Else Statement With While Loop
2.3.
Python
2.3.1.
Nested While Loop
2.4.
Python
2.5.
For Loop
2.5.1.
Flow Chart of for Loop
2.6.
Python
2.7.
Python
2.8.
Python
2.9.
Python
2.10.
Python
2.11.
Python
2.12.
Python
2.13.
Python
2.14.
Python
2.14.1.
Else Statement With For Loop
2.15.
Python
2.15.1.
Nested For Loop
2.16.
Python
2.17.
Loop Control Statements
2.17.1.
break
2.18.
Python
2.18.1.
continue
2.19.
Python
2.19.1.
pass
2.20.
Python
3.
Frequently Asked Questions
3.1.
What is a defined loop in Python?
3.2.
What is loop() used for?
3.3.
Why use Python for loop?
4.
Conclusion
Last Updated: Dec 26, 2024
Easy

Loops in Python

Author ANKIT KUMAR
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Before we move on to studying the various types of loops in Python, it is essential to understand what a loop is and why we even need loops. A loop in any programming language is a set of instructions that is repeated until a condition is true. In simple terms, loops are used to do a particular task multiple times. In software programming, there will always be situations where one has to do a specific task again and again. It is a very poor practice to copy-paste the code again and again. We should always follow the DRY (Don't Repeat Yourself) principle.

Loops in Python

Why are Loops Used?

  1. Suppose you need to scan the entire elements of an array. Trying to access each element by writing its index may be easy when the array size is relatively small, but what if the array size is in the range of lakhs. Is it an efficient way to manually index lakhs of array elements?
     
  2. Suppose we want to execute a certain piece of code until a condition is true. Manually calculating the condition every time is cumbersome. Loops are very helpful in such a situation.

You can also read about the Multilevel Inheritance in Python, Fibonacci Series in Python.

Types Of Loops In Python

Now that we have discussed why we need loops, it's time to discuss the various types of loops in Python.

WHILE LOOP

The while loop is a very common type of loop found in Python. We use a while loop mainly in cases where we do not have the exact idea when our iteration has to be stopped. Based on the condition provided, the while loop executes the statements inside the loop until the condition is true. Once the condition is false, the loop breaks, and the control comes out of the loop.

Syntax:

while expression:
       statements(code)

The while loop first checks the expression which is provided. If the expression evaluates to true, the statements inside the loop will be executed until the condition continues to be true. After that, control comes out of the loop.

Flow Chart of While Loop

Flow Chart of While Loop

Example:

  • Python

Python

iterating_Variable=1;
while (iterating_Variable < 6):
print("Coding ninjas blogs are the best resources to learn!")
iterating_Variable += 1
You can also try this code with Online Python Compiler
Run Code

Output:

Coding ninjas blogs are the best resources to learn!
Coding ninjas blogs are the best resources to learn!
Coding ninjas blogs are the best resources to learn!
Coding ninjas blogs are the best resources to learn!
Coding ninjas blogs are the best resources to learn!

Let's analyse the code we just wrote:

  • We first define a variable called “iterating_Variable” and assign a value 1 to it.
  • When the while loop checks the expression, it finds the expression to be true as iterating_Variable is set to 1 and is less than 6.
  • The control enters inside the loop and prints the line, "Coding ninjas blogs are the best resources to learn!"
  • Also, the value of iterating_Variable is increased by 1. At present, its value is 2 after the increment.
  • Again the expression is checked, the condition is fulfilled, and the print command is executed. After printing the line five times, the value of iterating_Variable becomes 6.
  • At this moment, the condition is not fulfilled as 6 is not less than 6. Hence the control now comes out of the loop. 

Single Statement While Loop

A single statement while loop consists of just a single line code.

Example:

itr_Var=True
while (itr_Var==True): print("Coding Ninjas")

Here, we have assigned True to itr_Var. The loop continues to execute the code inside its block until itr_Var is True. Such a loop is also known as an infinite loop, as it will never end. It will continue to print Coding Ninjas at the console. We can press the Ctrl+C key to exit.

Else Statement With While Loop

The else statement can be used along with the while loop to execute certain statements if the condition becomes false. It is executed immediately after the condition for the while loop becomes false.

Example:

  • Python

Python

count = 0
while (count < 3):  
   count = count + 1
   print("Coding Ninjas")
else:
   print("Out of the loop. Inside Else block")
You can also try this code with Online Python Compiler
Run Code

The output of the above code is:

Coding Ninjas
Coding Ninjas
Coding Ninjas
Out of the loop. Inside Else block

Once the count value becomes 3, the condition of the while loop is no longer true. Therefore, the statement in the else clause is executed. It is important to note that the else statement is not executed if we break from the loop or any exception occurs.

Nested While Loop

When a while loop is present inside another while loop, it is called a nested while loop. In most applications, we need nested loops.

Syntax:

while expression:         
  while expression:
          statement(s) 
statement(s)
You can also try this code with Online Python Compiler
Run Code

Example:

  • Python

Python

i=1
while i<=3 :
   print("OUTER loop number:",i)
   j=1
   while j<=3:
       print("Inner loop number: ",j)
       j+=1
   print("***************************")
   i+=1;
You can also try this code with Online Python Compiler
Run Code

The output of the above code is:

OUTER loop number: 1
Inner loop number:  1
Inner loop number:  2
Inner loop number:  3
***************************
OUTER loop number: 2
Inner loop number:  1
Inner loop number:  2
Inner loop number:  3
***************************
OUTER loop number: 3
Inner loop number:  1
Inner loop number:  2
Inner loop number:  3
***************************

In the above nested while loop, we have an outer loop and an inner loop. For every value of the outer loop, the inner loop is executed exactly three times. The iterating variables are incremented just as they are done in normal while loops.

For Loop

For loop is used in the case of sequential traversal. We generally use a for loop when we know when to start and, more importantly, when to end the loop. It is used for iterating over a sequence (that is, either a list, a tuple, a dictionary, a set, or a string).

Syntax:

for iterator_var in sequence:

    statements(s)

Flow Chart of for Loop

Flow Chart of for Loop

for loop can be better understood with the help of some examples.

Example 1: Looping Through a List.

The list is an iterable object. Hence we can use a for loop to iterate over the list.

  • Python

Python

myFavSubjects = ["DSA", "DBMS", "OOPS","WEB DEV"]
for subjects in myFavSubjects:
 print(subjects)
You can also try this code with Online Python Compiler
Run Code

Output:

DSA
DBMS
OOPS
WEB DEV

Steps involved in the above loop:

  • Using iter(), an iterator of the myFavsubjects collection is obtained.
  • An infinite while loop is run, and the built-in next() function obtains the next value from the iterator.
  • The loop ends only when the StopIteration Exception is raised.

The above code is equivalent to:

  • Python

Python

myFavSubjects = ["DSA", "DBMS", "OOPS","WEB DEV"]
myItr = iter(myFavSubjects)
while True:
 try:
     subject = next(myItr)
     print(subject)
 except StopIteration:
      break
You can also try this code with Online Python Compiler
Run Code

Example 2: Looping Through a String

A string is considered to be a sequence of characters. They are iterable objects. We can use a for loop to easily fetch each character in a string.

  • Python

Python

name = "CodingNinjas"
for characters in name:
   print(characters)
You can also try this code with Online Python Compiler
Run Code

Output: 

C
o
d
i
n
g
N
i
n
j
a
s

Example 3: Iterating Over a Tuple

Iterating over a tuple is as simple as iterating over a string.

  • Python

Python

tupleItems = ("Bat", "Bowl", "Wickets","Helmet")
for item in tupleItems:
 print(item)
You can also try this code with Online Python Compiler
Run Code

Output:

Bat
Bowl
Wickets
Helmet

Example 4: Iterating Over a Dictionary

Type 1:

  • Python

Python

dictionary = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
for key in dictionary:
    print(key)
You can also try this code with Online Python Compiler
Run Code

Output:

color
fruit
pet

Type 2:

  • Python

Python

dictionary = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
for key in dictionary:
    print(key ,'->', dictionary[key])
You can also try this code with Online Python Compiler
Run Code

Output :

color -> blue
fruit -> apple
pet -> dog

Example 5: Using range()

The range() function is a built-in Python function that is very commonly used with the for loop. It is used to generate a sequence of numbers from 0 by default up to a specified range. The range function takes in three parameters: range( start, stop, step).

  • start: It is an optional parameter that tells at which value the loop should start. Its default value is 0.
  • stop: It is a mandatory parameter. It tells us the position at which the loop must stop from executing further. The stop value is not included in the output.
  • step: It is also an optional parameter. It is used to specify the increment or decrement of the iteration variable. Its default value is 1.

Type 1:

  • Python

Python

for var in range(5):
   print(var)
You can also try this code with Online Python Compiler
Run Code

Output:

0
1
2
3
4

Type 2:

  • Python

Python

for var in range(1,6):
   print(var)
You can also try this code with Online Python Compiler
Run Code

Output: 

1
2
3
4
5

Type 3:

  • Python

Python

for var in range(2, 11, 2):
   print(var)
You can also try this code with Online Python Compiler
Run Code

Output:

2
4
6
8
10

Else Statement With For Loop

The else statement with for loop behaves exactly as it did with the while loop. The statements in the else block are executed after the loop execution is over after all the iterations are over.

Example:

  • Python

Python

myList=["laptop","keyboard","mouse"]
for item in myList:
   print(item)
else:
   print("Executing else block now...")
You can also try this code with Online Python Compiler
Run Code

The output of the above Python code will be:

laptop
keyboard
mouse
Executing else block now...

Nested For Loop

We also have the provision for nested for loop just as we had for the nested while loop. A for loop inside another for loop is known as the nested for loop.

Example:

  • Python

Python

for i in range(2):
   print("OUTER loop number: ",i+1)
   for j in range(3):
       print("Inner loop number: ",j+1)
   print("**********************")
You can also try this code with Online Python Compiler
Run Code

Output: 

OUTER loop number:  1
Inner loop number:  1
Inner loop number:  2
Inner loop number:  3
**********************
OUTER loop number:  2
Inner loop number:  1
Inner loop number:  2
Inner loop number:  3
**********************

 

You can try it on online python compiler.

Loop Control Statements

Consider a situation where you want to skip a particular iteration or want to stop the execution of the loop before its completion for some reason. The loop control statements come in handy in such a situation. Using loop control statements, we can alter the normal flow of the loop. The three main loop control statements in Python are:

break

The break statement is used to terminate the loop and bring the control out of the loop. It can be used in situations where the desired result is obtained, and we no longer want to execute the loop.

Example:

  • Python

Python

for var in range(1,10):
   if var==5:
       break
   print(var)
You can also try this code with Online Python Compiler
Run Code

Output:

1
2
3
4

The above loop should have printed 1 to 9 at the console. However, using the break statement, we forcibly stop the iteration when the value of var becomes equal to 5. The control of the program then comes out of the loop.

continue

The continue statement is used to skip the current iteration. Unlike break, it does not terminate the loop, just the current iteration is skipped, and the control goes back to the beginning of the loop.

Example:

  • Python

Python

for x in "Coding":
   if x=='i':
       continue
   print(x)
You can also try this code with Online Python Compiler
Run Code

Output: 

C
o
d
n
g

The above code will skip the iteration when x has the value “i”. Therefore we get the output with the character “i” missing.

pass

Pass statement in the loop is generally used to write empty loops. It is also used for empty control statements, functions, and classes.

Example:

  • Python

Python

for var in "passed":
   pass
print(var)
You can also try this code with Online Python Compiler
Run Code

Output:

s

Check out this article - Quicksort Python and Convert String to List Python.

Recommended Topic, Divmod in Python

Frequently Asked Questions

What is a defined loop in Python?

A defined loop in Python, such as a for loop, iterates over a sequence (list, tuple, string, etc.) with a predetermined range.

What is loop() used for?

loop() typically refers to repeating tasks indefinitely, often using constructs like while True: in Python or for defining iterative tasks in event-driven programming.

Why use Python for loop?

Python's for loop is efficient for iterating over sequences, offering clear syntax and built-in support for items like lists, dictionaries, and ranges.

Conclusion

  • A loop in any programming language is a set of instructions that is repeated until a condition is true.
  • The three main types of loops in Python are - for loop, while loop, nested loop.
  • Based on the condition provided, the while loop executes the statements inside the loop until the condition is true. 
  • For loop is used in the case of sequential traversal. 
  • Using loop control statements, we can alter the normal flow of the loop. The three main loop control statements in Python are: break, continue, and pass.
  • break is used to terminate the loop and bring the control out of the loop.
  • continue is used to skip the current iteration of the loop. The control goes back to the beginning of the loop.

You can also consider our paid courses such as DSA in Python to give your career an edge over others!

Happy learning!

Live masterclass