Loops in Python
a loop allows us to execute same statements multiple times,and reduces lie of code,and user-friendly ,any one can understand ,instead of rewriting same code multiple times we use loops
there are two types of loops
While Loop
For Loop
While Loop
the loop is controlled by the condition,as long as the condition is true the statement executes,when the condition is false then loop breaks
here,the first line is called while clause,whole indented lines are called body of the while loop.
first the while condition is evaluated ,its a Boolean expression so it returns True or False,If the condition is true than the indented lines body of the loop will be evaluated ,then again the controller goes to the condition of the loop and checks whether the condition is True or False ,if the condition is True than same process will be repeated and ,if the condition is False then the While Loop breaks.
Example
check out the while loop example for the sum until given number given above. Condition is I < x, by the end of the while loop there is an iteration, increasing I value by 1 for every loop and sum variable is updated with the addition of the next number in every loop. when the condition I < x fails then the while loop stops and controller goes to the next line after the while loop
For Loop
for loop is used for iterating sequences,because sequences re index in the number manner.
syntax is given below:**
we will discuss more about sequences in the coming posts,but now we will see example of for loop