python

Python While Loop

With the while loop we can execute a set of statements as long as a condition is true.
Syntax:


while condition: ​

    <indented statement 1> ​

    <indented statement 2>

    ... ​

    <indented statement n>

<non-indented statement 1>

<non-indented statement 2>
                

Some Important Points:
First the condition is evaluated. If the condition is true then statements in the while block is executed.
​ ​ After executing statements in the while block the condition is checked again and if it is still true, then the statements inside the while block is executed again. ​
​ The statements inside the while block will keep executing until the condition is true. ​
​ Each execution of the loop body is known as iteration.​
​ When the condition becomes false loop terminates and program control comes out of the while loop to begin the execution of statement following it.​

Example:

    
i=1​

while i<=10:​

    print(i)​

    i=i+1​

print("done!") 
    

Output:

    
1
2
3
4
5
6
7
8
9
10
done!        
    

Example:

    
i=1​

while i<=10:​

    print(i)​

i=i+1​

print("done!")  
    

Output:

    
1
1
1
1
1
1
1
1
.
.
.       
    

Another form of while loop

In Python , just like we have an else with if , similarly we also can have an else part with the while loop.​
The statements in the else part are executed, when the condition is not fulfilled anymore.

Syntax:

    
        

while condition: ​

    <indented statement 1> ​

    <indented statement 2> ​

    ... ​
    
    <indented statement n> ​

else:​

    <indented statement 1> ​

    <indented statement 2>

​    

Some Important Points:
Many programmer’s have a doubt that If the statements of the additional else part were placed right after the while loop without an else, they would have been executed anyway, wouldn't they.
​ ​ Then what is the use of else ​
​ To understand this , we need to understand the break statement. Our next tutorial is on Break and Continue statement and will help you understand this concept. ​