Python Looping

4 Min Read

1. For loop:

For loop is a conditional iterative statement which checks the condition and runs continuously until the condition gets true. Normally, it is preferable to iterate over a sequence as an example list, string, tuple, etc. Loop is used in various real life projects such as a software which allows users to try password for five attempts and block accounts, a song player which plays your favorite song repeat mode, an ATM machine, etc. 


num = [1, 2, 3, 4, 5]
sum = 0
for n in num:
    		sum = sum+n
print("The sum is", sum)


The sum is 15

In the above program, the elements of the list were added and printed. The sum variable is initialized as 0. After that, every element was added to the sum variable by for loop.

2. While Loop:

The statement which repeatedly runs while a condition is true is known as a while loop. Normally, a while loop is used when the number of iterations is unknown. (Eg: a program to guess a lucky number where the iteration is unknown).


i = 1
while i < 6:
  i = i + 1



In the above program, i is initialized as 1. After that, the condition i<6 is tested where it will print i and will be incremented by 1. The process continues until the statement is false. Similarly, the above program gets terminated after it increases to 6.

3. Nested loop:

A loop inside another loop is called a nested loop. Nested loop is used in a program to work upon multidimensional data structure (Eg: two-dimensional array). In the execution of a nested loop, the inner loop starts and finishes its execution.     


n = 5
for i in range(n+1):
    		for j in range(1, i+1):
        			print(i, end=' ')


2 2 
3 3 3 
4 4 4 4 
5 5 5 5 5 

The above is a program to print number patterns. The first for loop is the outer loop of the program where the second for loop is the nested loop.

4. Do while loop:

The do while loop is a loop which runs at least once and checks the condition which runs until the condition is met. The only difference between while loop and do while loop is that do while loop runs at least once before checking the condition. Python language does not have a do while loop but it can be created. 

Example: Age guessing program:


number = 19
count = 0

while True:
   		 num = int(input("Enter the number: "))
    		count = count + 1
    		if num == number:
        			print("You guessed it!")
    		if num != number and count > 4:
        			print("Try again!")


Enter the number: 19
You guessed it!

Above is the age guessing program which takes input numbers from the user and checks whether the input number is correct or not. If it matches the age, the program will get terminated. Else the user will get 5 chances, if the user did not guess it until 5 attempts, the program will get terminated.  

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *