In a programming language, there comes a case when we need to repeat some block of codes for a certain number of times or until some condition is met. Loops come in handy to do this operation in Python. The following flowchart describes the execution cycle of a loop.
Python provides two types of loop control statements.
- for loop
The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it offers.
Know more about Python for Loop Statements
- while loop
The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will be traversed.
Know more about Python while Loop Statements
What are the advantages of Loops
Loops provide a very handy tool for developers. Here are some of the advantages of loop control statement:-
- When a certain block of codes is repeated more than a time, the loop can help remove that repetition of codes.
- A loop allows the reusability of the code.
- Loop helps to traverse through data structures like list, tuple, string etc.
- Loop can help in solving different mathematical problems.
Every loop constitutes three main parts:
- Initialization: Every loop must have a starting point called initialization
- Test expression: It determines how many times a loop must execute. The loop continues as
long as the test expression is true.
- Update: A loop must be updated after the execution of certain statements to reach its final
destination. We may update the loop by increment, decrement operators or by using any other arithmetic operators.