Python For Loop
For loop in Python is used to iterate over the sequence of elements. The sequence can be a list, tuple or a string. We can also use loop to execute statements repeatedly.
Python for loop Syntax
Python for loop is slightly different than other programming language because it does not require to set indexing variable.
Python for loop Example
Let’s understand the working of for loop by a simple example.
Notice, it is so easy to use for loop and iterate over the list. No need to initialize and increment variable as we do in other programming languages.
Python for loop using range function
Range is a built-in function that returns an object of a sequence. It can be applied to for loop for iterating over the elements of the sequence. It is beneficial when we want to iterate over the integer values.
Python for loop Example
In this example, we created a range that starts from 1 and goes to 4. the last number is excluded, so the loop iterates till 4.
Python for loop with break statement
The break statement is used to terminate the loop execution. In for loop, we can use break to stop execution at certain condition. If you are using nested loop, only inner loop terminates.
Example
In the above example, loop iterates and when it encounter element 4, it breaks the loop and stops further execution.
Python for loop using continue Statement
continue is a keyword in python which is used to skip the current executing iteration and resume the execution from next iteration. It is mostly used in loops to manage loop’s execution flow.
Example
In this example, when loop reaches to third iteration, then it skips current iteration and start from the next iteration.
Python for using else Statement
Python allows to use else statement with for loop. The else block executes when the for loop is completed.
Example
You can see, in this example, when the for loop finished, else block executed.
Python Nested For Loop
Loop inside another loop forms a nested loop. We can have any number of loop inside the loop as per the program logic requirement but it is recommended not to use more nested loop because it makes program complex and difficult to debug.