While loop is used to execute repeated cod executions multiple times until the condition is satisfied.

While loop in Python

while loop executes code statements based on Conditions True value.

Syntax:

while Conditional_Expression:
    # Code Blocks

Conditional_expression evaluates to a Boolean Expression that contains True or False.

If the value is True, It executes code blocks, and Skip code execution, if the value is False

Code Blocks are multiple statement lines placed with indentation.

first = 0
while first < 5:
    first += 1
    print(first);

Output:

1
2
3
4
5

Do while loop in Python

A lot of programming languages provide a while and do while loop.

While loop executes conditional expression first, and executes code blocks for True values Do While loop first executes code blocks for a single time and runs again for True values.

Python has no syntax support for do a while loop.

Syntax:

condition = True while condition: do_stuff() condition = ()

One way, make the conditions value True in a while loop, It executes code blocks first next, check the condition expression using if and break the loop.

It always executes code statements once similar to doing a while loop.

first = 0
while True:
    first += 1
    print(first);
    if first < 5:
        break

Infinite while loop

Infinite loop execute code blocks infinite times and conditions in While always True.

while True:
    print("Loop");

Conditional value evaluated to Truth expression only.

Python While loop Break and Continue

Break: keyword used to break from a while loop and control goes to next line of while loop. Continue: skip the current iteration and execute the next line inside a while loop.

first = 0
while True:
    first += 1
    if first > 5:
        break
    print(first);

Continue

first = 0
while True:
    first += 1
    if first > 5:
        break
    print(first);

Else clause on Python while statement

Python supports else clause in while loop statements

Similar to if else, else in while allows executing code blocks for failure cases

while condition_value:
    ## Code for True cases
else:
    ## Code for False cases and exit while loop execution

else: block executes when the condition in the while loop is False

Here is an example The following code executes else block in the while loop

i = 100

while i < 10:
    print(i)
    i += 1
else:
    print('Else block in while loop')
print ('End of program')

Output:

Else block in while loop
End of program

Next, True case in the while loop

i = 0

while i < 10:
    print(i)
    i += 1
else:
    print('Else block in while loop')
print ('End of program')

Output:

0
1
2
3
4
5
6
7
8
9
Else block in while loop
End of program