Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
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.1.2.
Single Statement While Loop
2.1.3.
Else Statement With While Loop
2.1.4.
Nested While Loop
2.2.
For Loop
2.2.1.
Flow Chart of for Loop
2.2.2.
Else Statement With For Loop
2.2.3.
Nested For Loop
2.3.
Loop Control Statements
2.3.1.
break
2.3.2.
continue
2.3.3.
pass
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024

Loops in Python

Author ANKIT KUMAR
0 upvote

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.

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

Example:

iterating_Variable=1;
while (iterating_Variable < 6):
    print("Coding ninjas blogs are the best resources to learn!")
    iterating_Variable += 1

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:

count = 0
while (count < 3):   
    count = count + 1
    print("Coding Ninjas")
else:
    print("Out of the loop. Inside Else block")

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)

Example:

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;

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

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.

myFavSubjects = ["DSA", "DBMS", "OOPS","WEB DEV"]
for subjects in myFavSubjects:
  print(subjects)

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:

myFavSubjects = ["DSA", "DBMS", "OOPS","WEB DEV"]
myItr = iter(myFavSubjects)
while True:
  try:
      subject = next(myItr)
      print(subject)
  except StopIteration:
       break

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.

name = "CodingNinjas"
for characters in name:
    print(characters)

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.

tupleItems = ("Bat", "Bowl", "Wickets","Helmet")
for item in tupleItems:
  print(item)

Output:

Bat
Bowl
Wickets
Helmet

Example 4: Iterating Over a Dictionary

Type 1:

dictionary = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
for key in dictionary:
     print(key)

Output:

color
fruit
pet

Type 2:

dictionary = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
for key in dictionary:
     print(key ,'->', dictionary[key])

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:

for var in range(5):
    print(var)

Output:

0
1
2
3
4

Type 2:

for var in range(1,6):
    print(var)

Output: 

1
2
3
4
5

Type 3:

for var in range(2, 11, 2):
    print(var)

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:

myList=["laptop","keyboard","mouse"]
for item in myList:
    print(item)
else:
    print("Executing else block now...")

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:

for i in range(2):
    print("OUTER loop number: ",i+1)
    for j in range(3):
        print("Inner loop number: ",j+1)
    print("**********************")

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:

for var in range(1,10):
    if var==5:
        break
    print(var)

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:

for x in "Coding":
    if x=='i':
        continue
    print(x)

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:

for var in "passed":
    pass
print(var)

Output:

s

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

Recommended Topic, Divmod in Python

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

FAQs

  1. Why do we need loops in Python?
    Loops are required to execute certain statements multiple times without having to code it again and again.
     
  2. What are the types of loops in Python?
    The three main types of loops in Python are - for loop, while loop, nested loop.
     
  3. Why is the break statement used in loops?
    It is used to terminate the loop and bring the control out of the loop.
     
  4. What is a nested loop?
    A loop inside the body of another loop represents a nested loop. 
     
  5. What is the use of the continue statement in loops?
    It is used to skip the current iteration of the loop. The control goes back to the beginning of the loop.

Key Takeaways

  • 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!

Previous article
Short-Circuiting in Python
Next article
Break, Continue, Pass in Python
Live masterclass