python while loop with examples

In this tutorial, we are going to learn how to create a python while loop with the examples and Python's while loop allows you to repeatedly execute a block of code as long as a certain condition is 'true'.  

Python while loop syntax:




while condition:
    code block


The code block within the while loop will be executed as long as the condition is 'True'. It is important to include a way to change the value of the condition within the code block, or else the loop will never end and you'll be stuck in an infinite loop. Python while loop with Examples below see the codes.
 

Here's an example of a simple while loop in action:


count = 0

while count < 5:
    print("Execute loop", count)
    count = count + 1


Output:



Execute loop 0
Execute loop 1
Execute loop 2
Execute loop 3
Execute loop 4


This while loop will print out the numbers 0 through 4, because the condition 'count < 5' is 'True' for each of those values of 'count'. Once count becomes 5, the condition is 'False' and the while loop stops executing.

Details Examples :



increment = 1

cnt = 6

while increment <= cnt:

    print(increment)
    increment = increment + 1


increment = 1 | cnt = 6 | True |=> increment printed = 1 & increment is added to 2.

increment = 2 | cnt = 6 | True |=> increment printed = 2 & increment is added to 3.

increment = 3 | cnt = 6 | True |=> increment printed = 3 & increment is added to 4.

increment = 4 | cnt = 6 | True |=> increment printed = 4 & increment is added to 5.

increment = 5 | cnt = 6 | True |=> increment printed = 5 & increment is added to 6.

increment = 6 | cnt = 6 | False|=> increment printed = 6 & increment is added to 7 & Loop is terminated.
 
 

It's also possible to include an 'else' clause at the end of a while loop. The code block within the 'else' clause will be executed after the while loop has finished executing, but only if the condition for the while loop was never 'True'. Here's an example:


count = 0
while count < 5:
    print("Execute loop", count)
    count = count + 1
else:
    print('No value to Execute')

Output:



Execute loop 0
Execute loop 1
Execute loop 2
Execute loop 3
Execute loop 4
No value to Execute


In this example, the 'else' clause will never be executed because the condition 'count < 5' is always 'True' before count is incremented to a value of 5 or greater. 
 

Python while Infinite Loop



while  True: #the condition always true


It's important to use while loops with caution, as it's easy to create an infinite loop if the condition is always 'True' or if there is no way to change the value of the condition within the code block. Make sure to include a way to break out of the loop or change the condition in order to avoid getting stuck in an infinite loop and run infinite times the full of memory like matrix numbers.

I hope you will understanding how to create a Python's while loop with examples.

Previous Post Next Post