In this article we are going through Loop control flow statements in python. It is almost same as other programming language such as C, C++ or java etc.
Sometimes you must take control on program execution to run same set of code in a loop to get the desired output. To control the program execution, we have special utilities or statements called as “Control flow statements”
The loop statements while or for allow us to execute a statement(s) over and over. A loop is controlled by a boolean expression that determines how many time statements can be executed.
Python has two primitive loop commands:
1. WHILE Loop
While condition is true keep running the loop and exit as soon as the condition becomes false. The conditional while loop syntax is the same as for if-else and elif statements.
2. For Loop
Another loop statement – for, is best for when you determine in advance how many times you need to execute the block of statements placed in the loop.
It allows you to perform an operation on each element in a list or character in a string.
2.1 List – for loop
It’s very simplest method, all you need to do to specify complete list of items and it will be available in the loop.
Let’s take one more example-
2.2 Range – for loop
For loop with range, gives you flexibility to use the appropriate range of values and important thing is you can control that range using available options along with for.
- start_pos: Start position value should be excluded from range value when you specify value for steps otherwise it can be counted.
- end_pos: End position must be excluded from range value.
- steps: Steps value controls the range values.
Few more examples which will clear all your doubts if you have any!
Read More: Python break, continue and pass statements