Exploring New Techs!

Python - Loops

 


Hello Technotizers, this article is dedicated to loops in Python. Loops are used to perform a certain operation multiple times without writing the code again and again.

Python has two primitive loop commands:

  • ·         while loop
  • ·         for loop

 

1.    1.  The while loop:

While loop executes the code block as long as the condition given is true.

i = 1       
while(i<7): 
    print(i)
    i=i+1   

The output is obtained as:

1  
2  
3  
4  
5  
6  

If we miss to increment the variable, the loop continues forever because the condition will be always True.

 

·         The break statement:

Break keyword is used to stop the execution of the loop even if the while condition is True.

i = 1        
while(i<7):  
    print(i) 
    if i==4
        break
    i=i+1    

The output is obtained as:

1  
2  
3  
4  

Here the execution stops when the variable becomes equal to 4.

 

·         The continue statement:

continue keyword is used to stop the execution of the current iteration and move to the next.

i = 1           
while(i<7):     
    i=i+1       
    if i==4:    
        continue
    print(i)    

The output is obtained as:

1  
2  
3  
5  
6  
7  

Here the execution stops when the variable becomes equal to 4 and jumps to the next iteration.

 

·         The else statement:

else keyword is used to execute a code block once the while condition is no longer True.

i = 1                               
while(i<=7):                        
    print(i)                        
    i=i+1                           
else:                               
    print("i is now greater than 7")

The output is obtained as:

1                      
2                      
3                      
5                      
6                      
7                      
i is now greater than 7

Here as soon as the while condition becomes False, the else code block executes.

 

2.    2.  The for loop:

      A for loop is used to iterate over a sequence that is list, tuple, set or string. It executes a code block once for each item in the sequence.

 

city = ['Mumbai','Delhi','Chennai','Kolkata']
for i in city:                               
    print(i)                                 

The output is obtained as:

Mumbai 
Delhi  
Chennai
Kolkata

Here ‘i’ is the iterating variable and each item is printed on a new line.

 

·         The break statement:

The break keyword is used to stop the for loop before iterating over all the items.

city                                  ['Mumbai','Delhi','Chennai','Kolkata']
for i in city:                        
    print(i)                          
    if i=='Chennai':                  
        break                         

The output is obtained as:

Mumbai   
Delhi    

Here the execution of the loop stops as soon as the variable becomes equal to ‘Chennai’.

 

·         The continue statement:

continue keyword is used to stop the execution of the current iteration and move to the next.

city =                                 ['Mumbai','Delhi','Chennai','Kolkata']
for i in city:                        
    if i=='Chennai':                  
        continue                      
    print(i)                          

The output is obtained as:

Mumbai    
Delhi     
Kolkata   

Here the execution stops when the variable becomes equal to ‘Chennai’ and jumps to the next iteration.

 

·         The range function:

The range function is used to get a sequence of numbers, beginning from 0 by default incrementing by 1 and ending at a specific number, which is not included in the sequence. The starting number and increment value can also be specified.

#default start=0 and increment=1            
for i in range(6):                          
    print("With default conditions:")       
    print(i)                                
#starting number is specified as 1          
for i in range(1,6):                        
    print("With specified starting number:")
    print(i)                                
#increment is specified as 2                
for i in range(1,6,2):                      
    print("With specified increment:")      
    print(i)                                

The output is obtained as:

With default conditions:       
0                              
1                              

2                              
3                              
4                              
5                              
With specified starting number:
1                              
2                              
3                              
4                              
5                              
With specified increment:      
1                              
3                              
5                              

Here various conditions can be specified for various sequences and writing a separate code for obtaining number sequences can be avoided.

.

·         The else statement:

else keyword is used to execute a code block once the loop is finished.

for i in range(6):             
    print(i)                   
else:                          
    print("Sequence finished.")

The output is obtained as:

0                 
1                 
2                 
3                 
5                 

Sequence finished.

Here as soon as the for loop end, the else code block executes.

 

·         Nested for loop:

A for loop inside another for loop is called as nested for loop. The inner loop is executed once for every iteration of the outer loop. The next iteration of the outer loop is only possible when the inner loop completes all its iterations.

quality = ['big','small','beautiful'
city =                                 ['Mumbai','Delhi','Chennai','Kolkata']
for i in quality:                     
    for j in city:                    
        print(i,j)                    

The output is obtained as:

big Mumbai        
big Delhi         
big Chennai       
big Kolkata       
small Mumbai      
small Delhi       
small Chennai     
small Kolkata     
beautiful Mumbai  
beautiful Delhi   
beautiful Chennai 
beautiful Kolkata 

Here two variables ‘I’ and ‘j’ are used as iteration variables as the code contains two for loops. Each city gets each of the quality present in the list and is printed accordingly.

 

Another example:

Let’s generate an interesting pattern using nested loops:

for i in range(0,6):           
        num = 1                
        for j in range(0, i+1):
            print(num, end=" ")
            num = num + 1      
        print("\r")            

The output is obtained as:

1            
1 2          
1 2 3        
1 2 3 4      
1 2 3 4 5    
1 2 3 4 5 6  

Here end=” “ is used for printing on the same line and “\r” is used for ending line after each row. Do try another such patterns by the changing the conditions in the code!!


With this we come to an end of this article. Hope it was helpful. Do provide your feedback and ideas through comments, it would be highly appreciated.

See you soon!

Keep coding and exploring new techs!!

 

 

 

0 comments:

Post a Comment