Python While Loop


Python While Loop

While loop is used when we want to perform iterations. It can repeat the statement or group of statements until the condition is true. As soon as the condition becomes false, it will stop iterating.

In the while loop, it is mandatory to declare from where to start and the condition at which we would like to stop.

Python While Loop

Below is the example of a while loop in which we are starting at a = 0, the condition to terminate the while loop is a <= 0. Note: In the while block, the variable 'a' is getting incremented by 1, which is a must, otherwise the while loop will get into an infinite loop.

In [1]:
a = 0

while a <= 5:
    print(a)
    a = a + 1
0
1
2
3
4
5

while with string

While loop can also be used to traverse the sequences, for example, string, list, tuple, etc. To achieve this, we can take help from range function and string index positions. Let’s take a look at the example below:

In [1]:
a = 0
s = "Logical Python"
while a < len(s):
    print(s[a])
    a = a + 1
L
o
g
i
c
a
l
 
P
y
t
h
o
n

while with else

This while else is used when we want to do some task after the while loop is done with its iterations. The else block will execute only if the while loop is successfully able to complete all the iterations without any error, exception, break statement, etc. If while cannot complete all iterations, else block will not get executed.

Here, else block saying, “Done!! We are Good” got successfully executed.

In [1]:
a = 1

while a <= 5:
    print(a)
    a = a+1
    
else:
    print('Done!! We are Good.')
1
2
3
4
5
Done!! We are Good.

Here, else block is not executed because we used the break statement when a = 3.

In [2]:
a = 1

while a <= 5:
    print(a)
    if a == 3:
        break
    a = a+1
    
else:
    print('Thanks for visiting')
1
2
3

Single Statement While

We can write the content of a while loop in a single statement. Each statement inside a while loop block has to be separated using the semicolon(;)

In [1]:
a = 1

while a <= 5: print(a);   a = a+1
1
2
3
4
5

Infinite While loop

It is very important to update the condition variable inside the loop so that the loop can stop at some point. Otherwise, the loop will run infinite times until the memory is full. In this case, we have to manually stop/terminate the session.

In the below example, we have manually terminated the loop.

Infinite while loop. Removed iterations for sake of presentation.

In [1]:
i = 1

while i <= 5:
    print(i)
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-1-e85785c92f02> in <module>
      2 
      3 while i <= 5:
----> 4     print(i)

~\Anaconda3\lib\site-packages\ipykernel\iostream.py in write(self, string)
    400             is_child = (not self._is_master_process())
    401             # only touch the buffer in the IO thread to avoid races
--> 402             self.pub_thread.schedule(lambda : self._buffer.write(string))
    403             if is_child:
    404                 # newlines imply flush in subprocesses

~\Anaconda3\lib\site-packages\ipykernel\iostream.py in schedule(self, f)
    203             self._events.append(f)
    204             # wake event thread (message content is ignored)
--> 205             self._event_pipe.send(b'')
    206         else:
    207             f()

~\Anaconda3\lib\site-packages\zmq\sugar\socket.py in send(self, data, flags, copy, track, routing_id, group)
    398                                  copy_threshold=self.copy_threshold)
    399             data.group = group
--> 400         return super(Socket, self).send(data, flags=flags, copy=copy, track=track)
    401 
    402     def send_multipart(self, msg_parts, flags=0, copy=True, track=False, **kwargs):

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.send()

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.send()

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket._send_copy()

~\Anaconda3\lib\site-packages\zmq\backend\cython\checkrc.pxd in zmq.backend.cython.checkrc._check_rc()

KeyboardInterrupt: 

Finite while loop

In [2]:
i = 1

while i <= 5:
    print(i)
    i = i + 1
1
2
3
4
5

Python For loop vs While loop

Here are a few differences between the python for loop and while loop.

ParameterFor LoopWhile Loop
KeywordFor Keyword is used.While Keyword is used.
When to UseThe number of iterations already known.The number of iterations is not known
IterationEvery element is fetched through the iterator/generator. Example, range()Every element is explicitly incremented or decremented by the user
InitializationOnly once at the start of the loop.Repeat at every iteration.
Generator SupportFor loop supports generators in Python.While loop does not support Generators directly.
EfficiencyMore efficient when iterating over sequences due to predetermined iterations.Efficient in situations only where the stop condition needs to be evaluated.
Loop NatureUsed to iterate over a fixed sequence of items.Used when we don’t know the number of iterations.
SpeedFor loop is faster than a while loop.While loop is slower as compared to for loop.

References

  1. Python While Loops
  2. More Control Flow Tools