Python while loop tutorial.
A loop provides the functionality to execute a code block again and again. In Python, we have two looping techniques.
- Finite loop – At the start of execution, a programmer 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 Python and execution flow control using 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 >
Following is an example of the while loop that has five iterations.
maxIteration = 5;
while maxIteration > 0:
maxIteration = maxIteration -1;
print(maxIteration);
print("Code after loop body");
4
3
2
1
0
Code after loop body
Following is the step-by-step execution analysis for the while loop.
- An integer variable
maxIteration
is initialized to five. - Expression maxIteration > 0 returns true, and control enters inside the loop body.
- Loop Body executes (maxIteration decrements by one, and its value is printed on the console).
- Control reaches the start line having the condition(while maxIteration > 0:) for the loop and is reevaluated.
- The code within the loop executes again and again till the expression (
maxIteration > 0
) returning true. - The
maxIteration
, becomes less than zero (maxIteration > 0 returns false) after five iterations. Control comes out from the loop 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");
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
- On execution of the Continue statement, execution reaches 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