Dev ❤ Ops

While loop in python

A while loop in Python allows you to repeatedly execute a block of code as long as a certain condition is True.

Here is the basic syntax for a while loop:

while condition:
    # code to be executed

The code within the loop will be executed repeatedly as long as the condition is True. Once the condition becomes False, the loop will terminate and the program will continue with the next statement after the loop.

Here is an example of a while loop that counts from 1 to 10:

i = 1
while i <= 10:
    print(i)
    i += 1

This loop will print the numbers 1 through 10 to the console. The loop variable i is initialized to 1, and the loop will continue as long as i is less than or equal to 10. The value of i is incremented by 1 at the end of each iteration using the i += 1 statement. When i becomes greater than 10, the loop will terminate.

It is important to make sure that the condition in a while loop eventually becomes False, or else the loop will run indefinitely, which is known as an infinite loop.

You can use the break statement to exit a while loop prematurely, and the continue statement to skip the rest of the current iteration and move on to the next one.

For more information please visit python.org

This article is created based on experience but If you discover any corrections or enhancements, please write a comment in the comment section or email us at contribute@devopsforu.com. You can also reach out to us from Contact-Us Page.

Follow us on LinkedIn for updates!

Leave a comment

Your email address will not be published. Required fields are marked *