Python Loops

In this tutorial, we will learn about Loops in Python and we will also cover different examples related to Python Loops. And, we will cover these topics.

  • Python Loops
  • Why do we use loops in python?
  • Advantages of loops
  • Python for loop
  • Nested for loop in python
  • Using else statement with for loop
  • Python While loop
  • Loop Control Statements
  • Infinite while loop
  • Using else with while loop

Python Loops

The course of Programming is in a sequential manner and when the programmers or the developer’s code there is a need to repeat the upper written code again and again and to solve this we started using the Loops.

The Various types of Loops are provided by the programming languages which is suited to repeating the specific line of code as many times as we want.

How we use the loops can be better understood using the following diagram:

Python Loops
Python Loops

Why do we use loops in python?

Loops are a very important part of Python or in any other language, with the help of loops, we can use the same line of code several times which saves time and also decrease the line of code.

For Example, If we want to print the series of numbers and we use the normal line of code which takes a lot of lines to print the series but if we use the loops we can run the same line of code several times as many as we want to print.

Advantages of loops

Working with loops is having good advantages through which some are given below:

  • With the help of loops we can run the same line of code several times.
  • It saves the time.
  • It makes the code look clean.

The loops are of three types:

  • For Loop
  • While Loop
  • Do-While Loop
Loop statementDescription
For LoopFor Loop is used for iterating the sequence it executes the set of statements and it is used in list, tuple, and set.
While LoopIt is used when we don’t know the number of iteration in advance. In this, the code is only executed when the condition is satisfied in the while loop.
Do-While LoopThe do-while loop is also known as the post-tested loop. It works until the conditions get satisfied.

Python for loop

The For Loop is used for iterating the sequence it executes the set of statements and it is used in list, tuple, and set.

For Loop Syntax:

for iterating_var in sequence:    
    statement(s)
Python For Loop
Python For Loop

For Loop Using the Python and Examples

Example 1: Iterating string using for loop

string = "PythonTpoint"  
for i in string:  
    print(i)  

Output:

Iterating string using for loop
Iterating string using for loop

Example 2: Program to print the table of the given number.

add_list = [1,2,3,4,5,6,7,8,9,10]  
n = 15  
for i in add_list:  
    c = n*i  
    print(c)  
Python Table using for Loop
Python Table used for Loop

Example 3: Program to print the total of the given list.

Code:

py_list = [10,15,23,43,52]  
total = 0  
for i in py_list:  
    total = total+i  
print("The Total is:",total)

Output:

Python Total of Number using For Loop
Python Total of Number using For Loop

For loop Using range() function

In Python For loop, we use the Range() function to produce the sequence of the numbers which means if we use the range(10) then it will produce the range from 0 to 9.

Syntax:

range(start,stop,step size)
  • Start Represent the beginning of the iteration
  • The stop will represent the loop that will iterate till the stop.
  • Step size is used to skip the specific number from the iteration.

Python Range() function and its Example

Example 1: Program to print numbers in sequence.

for i in range(10):  
    print(i,end = ' ')  

Output:

Python range() function
Python range() print numbers

Example 2: Program to print table of the given number.

Code:

t = int(input("Enter the number "))  
for i in range(1,11):  
    c = t*i  
    print(t,"*",i,"=",c)  

Output:

Python program to print table
Python program to print table

Example 3: Program to print even number using step size in range().

Code:

t = int(input("Enter the number "))  
for i in range(2,t,2):  
    print(i)  

Output:

Step Size in Range()
Step Size in Range()

Nested for loop in python

In python it allows us to nest any number of loops inside for loop at here the inner loop is executed n number of times after every iteration of the outer loop.

Syntax:

for iterating_var1 in sequence:  #outer loop  
    for iterating_var2 in sequence:  #inner loop  
        #block of statements     
#Other statements    

Here are some examples of nested loops which we are going to explain:

Example 1: Nested for loop

Code:

# User input for number of rows  
r = int(input("Enter the rows:"))  
# Outer loop will print number of rows  
for i in range(0,r+1):  
# Inner loop will print number of Astrisk  
    for j in range(i):  
        print("*",end = '')  
    print()  
Python Pyramid using nested loop
Python Pyramid using nested loop

Example 2: Program to number pyramid.

Code:

r = int(input("Enter the rows"))  
for i in range(0,r+1):  
    for j in range(i):  
        print(i,end = '')  
    print()  

Output:

Python number pyramid using nested loop
Python number pyramid using nested loop

Using else statement with for loop

In python it allows us to use the else statement with using the for loop as we do in other languages like c, c++, java, etc. it is only used when all the iterations are finished. We also need to take care of this if inside the code we use the break statement then we won’t be able to execute the else statement.

Revise: Python If-else statements

Example of else without using the break statement.

Code:

for i in range(0,5):    
    print(i)    
else:  
    print("for loop is exhausted, because of no break statement.")  
Else statement Else statement with for loopwith for loop
Else statement with for loop

Example of else using the break statement.

for p in range(0,5):    
    print(p)
    print("The loop is broken due to break statement & came out of the loop")        
    break;    
else:print("for loop is Finished");    

Output:

Else using the break statement
Else using the break statement

Python While loop

It is used when we don’t know the number of iteration in advance. In this, the code is only executed when the condition is satisfied in the while loop. It is also known as the pre-tested loop.

Syntax:

while expression:    
    statements   

We can better understand with the help of the following flowchart:

While loop Flowchart
While loop Flowchart

Loop Control Statements

In python, we can change the normal sequence of the while loop using the loop control statements. In python, it offers the following loop control statements:

  • Continue Statement
  • Break Statement
  • Pass Statement

Continue Statement

In the Continue Statement when it is encountered, the control is transferred to the beginning of the loop. Let’s better understand with the following example:

Code:

i = 0  
str1 = 'pythontpoint'  
  
while i < len(str1):   
    if str1[i] == 'a' or str1[i] == 't':   
        i += 1  
        continue  
    print('Current Letter :',str1[i])   
    i += 1 

Output:

Continue Statement Example
Continue Statement Example

Break Statement

When the break is encountered the code is taken out from the loop.

Code:

i = 0  
string = 'pythontpoint'  
  
while i < len(string):   
    if string[i] == 't':   
        i += 1  
        break  
    print('Current Letter :', string[i])   
    i += 1  

Output:

Break Statement Example
Break Statement Example

Pass Statement

In python, the pass statement is used to declare the empty loop. It is also used to define the empty class, function and control statement. We can better understand with the following example:

Code:

string = 'pythontpoint'  
i = 0  
  
while i < len(string):   
    i += 1  
    pass  
print('Value of i :', i)  

Output:

Pass Statement Example
Pass Statement Example

Infinite while loop

In python while loop, if the condition is not false then the infinite loop will occur and it will never stop. now we will discuss more about the infinite loop using some example:

Code:

while (1):    
    print("Hi! we are inside the infinite while loop")  

Output:

Infinite while loop Example
Infinite while loop Example

Using else with the while loop

In python it allow us to use the else statement with the while loop. It is only executed when the the condition in the while statement is false like for loop in while loop if we use the break statement then it will not execute the else block and exit us from the code. we can better understand with the following example:

p =1    
while(p<=5):    
    print(p)    
    p=p+1    
    if(p==3):    
        break   
else:  
    print("The while loop exhausted")  
python while loop using else
python while loop using else

So, in this tutorial, we discussed Python Loops and we have also covered different examples related to its implementation. Here is the list of examples that we have covered.

  • Why do we use loops in python?
  • Advantages of loops
  • Python for loop
  • Nested for loop in python
  • Using else statement with for loop
  • Python While loop
  • Loop Control Statements
  • Infinite while loop
  • Using else with the while loop

436 thoughts on “Python Loops”

  1. My friend wants to read a story I wrote in a video on her Youtube channel. I’m concerned that my story could be stolen by some one, and have them claim it as their own, not that I think it’s really good enough for anyone to want to steal it. How likely do you think it would be that my story would be plagiarized? Is there anything Youtube does to try to stop plagiarism?.

    Reply

Leave a Comment