FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

While Loop




While loop is used to iterate over a block of code repeatedly until a given condition returns false. In the last tutorial, we have seen for loop in Python, which is also used for the same purpose. The main difference is that we use while loop when we are not certain of the number of times the loop requires execution, on the other hand when we exactly know how many times we need to run the loop, we use for loop.

Syntax of while loop

while condition:
    #body_of_while

The body_of_while is set of Python statements which requires repeated execution. These set of statements execute repeatedly until the given condition returns false.Lets take few examples of for loop to understand the usage.

Flow of while loop

1. First the given condition is checked, if the condition returns false, the loop is terminated and the control jumps to the next statement in the program after the loop.
2. If the condition returns true, the set of statements inside loop are executed and then the control jumps to the beginning of the loop for next iteration.
These two steps happen repeatedly as long as the condition specified in while loop remains true.

Python – While loop example

Here is an example of while loop. In this example, we have a variable num and we are displaying the value of num in a loop, the loop has a increment operation where we are increasing the value of num. This is very important step, the while loop must have a increment or decrement operation, else the loop will run indefinitely, we will cover this later in infinite while loop.

num = 1
# loop will repeat itself as long as
# num < 10 remains true
while num < 10:
    print(num)
    #incrementing the value of num
    num = num + 3

Output

1
4
7

while True:
   print("hello")

Example 2:

num = 1
while num<5:
   print(num)

This will print ‘1’ indefinitely because inside loop we are not updating the value of num, so the value of num will always remain 1 and the condition num < 5 will always return true.

Nested while loop in Python

When a while loop is present inside another while loop then it is called nested while loop. Lets take an example to understand this concept.

i = 1
j = 5
while i < 4:
    while j < 8:
        print(i, ",", j)
        j = j + 1
        i = i + 1

Output:

1 , 5
2 , 6
3 , 7

Python – while loop with else block

We can have a ‘else’ block associated with while loop. The ‘else’ block is optional. It executes only after the loop finished execution.

num = 10
while num > 6:
   print(num)
   num = num-1
else:
   print("loop is finished")

Output

10
9
8
7
loop is finished






Leave Comment