Python while loop tutorial.


A loop provides the capability to execute a code block again and again.  In python, we have two looping techniques. 

  • Finite loop – At the start, we can set the maximum number of iterations along with the condition,  E.g for loop
  • Infinite loop – At the start, we can set only a condition. So loop executes as long as the condition is true.  

While loop is an indefinite loop type. In this tutorial, we will learn how to use a while loop in a program.  Execution flow control (break, continue keywords). 

Syntax and basic example :

Syntax –

while expression:
      statement 1 with in loop;
      statement 2 with in loop;
      ....
      statement N with in loop;
<code after loop >
maxIteration = 5;
while maxIteration > 0:
	maxIteration = maxIteration -1;
	print(maxIteration);
	
print("Code after loop body");

Output ->

4
3
2
1
0
Code after loop body
  1. An integer variable maxIteration is initialized to five.
  2. Expression maxIteration > 0, returns true, and control enters the loop body.
  3. Loop Body executes (maxIteration decrements by one and its value is printed on the console).
  4. Control reaches the start (while maxIteration > 0:) of the loop and the reevaluated.
  5. The code with in loop executes again and again till the expression (maxIteration > 0) returning true.
  6. The maxIteration, becomes less than zero after 5 iterations. Loop ends and statement (print("Code after loop body");) just after the body executes.

Multiple Conditions in expressions-

The conditional expression may contain multiple subexpressions with logical operators.

maxIteration = 5;
printIterartion = True;
while maxIteration > 0 and printIterartion :
	maxIteration = maxIteration -1;
	print(maxIteration);
	
print("Code after first loop body");

printIterartion = False;
while maxIteration > 0 and printIterartion :
	maxIteration = maxIteration -1;
	print(maxIteration);
	
print("Code after second loop body");

Output->

4
3
2
1
0
Code after first loop body
Code after second loop body

Break and Continue:

Loop executes the block and checks the condition. Break and continue are the two statements to alter the flow.

  • With the break statement control comes out from the body of the loop.
  • Once the break is encountered, the execution jumps to the first statement after the loop.
maxIteration = 5;

while maxIteration > 0:
	maxIteration = maxIteration -1;
	if maxIteration == 2:
		break;
	print(maxIteration);
	
print("Code after first loop body");
4
3
Code after first loop body
  • Continue statement is to jump to the start of the loop.
maxIteration = 5;

while maxIteration > 0:
	maxIteration = maxIteration -1;
	if maxIteration == 2:
		continue;
	print(maxIteration);
	
print("Code after first loop body");
4
3
1
0
Code after first loop body