Python while Loop Statements

While loop is used in Python to repeat a block of code until the condition in while statement is true. It is also used quite frequently in Python.

Loading...

The syntax of while in python is given below.

while test_expression:
loop body
Let us browse some examples to get a clearer picture of the while loop in Python.
Example 1:- Print from 1 to 5 using while loop
i=1;  
while i<=5:  
    print(i);  
    i=i+1;
1
2
3
4
5

while loop with else

We can use an optional block with a while loop that will execute once the loop is terminated. But one thing to notice is that, if the loop contains any loop control statement ( i.e. break, continue or pass ), then the else block is not executed.

i = 1
while i<=5:  
    print(i)
    i = i + 1
else:
    print("Loop terminated")
1
2
3
4
5
Loop terminated
Loading...
SHARE Python while Loop Statements

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Share