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.
Let's see the syntax of for loop in Python.
Python for loop is slightly different than other programming language because it does not require to set indexing variable.
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.
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.
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.
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.
In the above example, loop iterates and when it encounter element 4, it breaks the loop and stops further execution.
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.
In this example, when loop reaches to third iteration, then it skips current iteration and start from the next iteration.
Python allows to use else statement with for loop. The else block executes when the for loop is completed.
You can see, in this example, when the for loop finished, else block executed.
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.