while Loop


Python while loop iterates the block of code repeatedly till it satisfies the specified condition. It is used when the number of iterations is not known before.

Syntax:

    while expression:
    	# statements

Example:

    i = 1
    while i < 5
        print(i)
        i++

Output:

    1
    2
    3
    4


Infinite while loop

Any non-zero value in the while loop indicates an always true condition whereas 0 indicates an always false condition.

Example:

    while(2)
    print(“This is infinite while loop”)    

Output:

    This is infinite while loop
    This is infinite while loop
    (infinite times)



else statement with while loop

Python allows us to use the else statement with the while loop which is executed only when the condition given in the while statement becomes false, But if the while loop contains any break statement then the else statement will not be executed.

Example:

    i = 1
    while i < 5
        print(i)
        i++
    else:print(“while loop is exhausted”)        

Output:

    1
    2
    3
    4        

Example:

    i = 1
    while i < 5
        print(i)
        i++
        if(i==3)
            break;
    else:print(“while loop is exhausted”)        

Output:

    1
    2
    Loop is broken due to break statement