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.
- Syntaxfor i in range condition:
- statement
Example
Here's a simple program for the "for loop”.
- for i in range(1,15):
- print(i)
Output
Remember that i's value is 15, so the block of code will be executed 15 times.
For Loop and Break statement
With the break declaration, we can stop the loop even if the while condition is true.
Syntax
- for i in range condition:
- if condition:
- break
Example
Here's a simple program for the "for loop” and “break statement”
- for i in range(1,15):
- if i == 6:
- break
- 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 and Continue Statement
The continue statement is used to leave a sum statement, then it continues with the next statement.
- Syntaxfor i in range condition:
- if condition:
- continue
Example
Here's a simple program for the "for loop” and “condition statement”.
- for i in range(1,15):
- if i == 6:
- continue
- print(i)
Output
Note that the number 6 is missing in the output.
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
- for i in range condition:
- if condition:
- pass
Example
Here's a simple program for the “for loop” and “pass statement”.
- for i in range(1,15):
- if i == 6:
- pass
- print(i)
Output
Pass statements do not change anything.
For Loop and Else Statement
In the else statement, we will run a block of code once while the condition is false.
- Syntaxfor i in range condition:
- statement
- else:
- statement
Example
Simple program for ”for loop “and “else statements”.
- for i in range(1,10):
- print(i)
- else:
- 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.
Conclusion
In this article, we have seen the for loop in Python. I hope this article was useful to you. Thanks for reading!