For Loop in Python

Introduction

 
In this article, I will explain the for loop in Python. For loops are used for sequential traversal. For example: traversing a listing or string or array etc. In Python, there may be no C style. For a loop example: for (i=0; i<n; i + +) there is a” for in” loop, which is just like a for each loop in other languages. Let's discover ways to use a for-in loop for sequential traversals. A for statement is executing within the inside statement once or more. Once False, the next code will be executed.
 
For Loop In Python
  1. Syntaxfor i in range condition:    
  2.        statement  
Example
 
Here's a simple program for the "for loop”.
  1. for i in range(1,15):  
  2.     print(i)  
Output 
 
Remember that i's value is 15, so the block of code will be executed 15 times.
 
For Loop In Python
 

For Loop and Break statement

 
With the break declaration, we can stop the loop even if the while condition is true.
 
Syntax
  1. for i in range condition:  
  2.    if condition:  
  3.    break  
Example
 
Here's a simple program for the "for loop” and “break statement”
  1. for i in range(1,15):  
  2.   if i == 6:  
  3.     break  
  4.   print(i)  
Output
 
Note that it runs up until the number 6, and after the number, there's no display in the Output screen.
 
For Loop In Python
 

For Loop and Continue Statement

 
The continue statement is used to leave a sum statement, then it continues with the next statement.
 
  1. Syntaxfor i in range condition:  
  2.    if condition:  
  3.    continue  
Example
 
Here's a simple program for the "for loop” and “condition statement”.
  1. for i in range(1,15):  
  2.   if i == 6:  
  3.     continue  
  4.   print(i)  
Output
 
Note that the number 6 is missing in the output.
 
For Loop In Python
 

For Loop and Pass Statement

 
The pass statement is used to write an empty loop statement. Pass is also used for empty control statements.
 
Syntax
  1. for i in range condition:  
  2.    if condition:  
  3.    pass  
Example
 
Here's a simple program for the “for loop” and “pass statement”.
  1. for i in range(1,15):  
  2.   if i == 6:  
  3.     pass  
  4.   print(i)  
Output
 
Pass statements do not change anything.
 
For Loop In Python
 

For Loop and Else Statement

 
In the else statement, we will run a block of code once while the condition is false.
 
  1. Syntaxfor i in range condition:    
  2.    statement  
  3. else:    
  4.    statement  
Example
 
Simple program for ”for loop “and “else statements”.
  1. for i in range(1,10):  
  2.   print(i)  
  3. else:  
  4.   print ("hello c#")  
Output 
 
Remember, i's value is 10, so the block of code will be executed 10 times. Then the else code will be executed one time.
 
For Loop In Python
 

Conclusion

 
In this article, we have seen the for loop in Python. I hope this article was useful to you. Thanks for reading!


Recommended Free Ebook
Similar Articles