/* */ Click to Join Live Class with Shankar sir Call 9798158723

while Loop in python


A while loop is a control statement using which the programmer can give instructions to the computer to execute a set of statement repeatedly as long as specified condition is satisfied. Ones the specified condition is false control comes out of the loop.

Syntax:-


whilecondition:

     Statement….
    updating


Note:-four space are python

how do you start writing a while loop in python?

  • Step 1:-
    The initialization statement is executed first
  • Step 2:-
    Then, the test expression is evaluated. If the test expression is evaluated to false, then the while loop gets terminated and the control comes out of the while loop.
  • Step 3:-
    if the test expression is evaluated to true,The statements defined inside the while loop will repeatedly execute until the given condition fails.
  • Step 4:-
    After successful execution of statements inside the body of the while loop, the update expression is executed.
  • Step 5:-
    Again the test expression is evaluated.

Example with dry Run Concepts


steps-shineskill


Note:

"When we do not know exactly how many times a set of statements have to be repeatedly executed, in such a situation we use while-loop."


Q.) W.A.P to print 1 to 5.
 
 
 i=1;
 while i<=5:
   print(i);
   i=i+1   
 
 
Output
 1 2 3 4 5

Program Explanation
  • Step 1:-
    We declared variables called i. The initialization statement is executed. i.e i=1
  • Step 2:-
    Then, the test expression is evaluated. i.e i is less than or equals to 5 or not (i <=5 ) hear condition is true so statements inside the body of the while loop are executed, and it will print the value of i i.e 1
  • Step 4:-
    After successful execution of statements inside the body of the loop, the update expression (i.e i++) means it incremented by 1 now the value of i is 2
  • Step 5:-
    Again the test expression is evaluated. and repeat step 2 till the condition is false
  • Step 5:-
    when the condition is false means the value of i will be 6 then while loop gets terminated and the control comes out of the loop.