while loop in Python

In programming, while loop keeps running the statements (code) as long as the given condition is true. To start, it checks the condition. Then, it moves on to follow the steps

Inside the while loop, we can make as many statements as we want to make. If we want, the situation could be any way we want it to be. It stops when the condition is false, and the next line of code is run.

When the condition is TRUE, it runs the conditional code. If the condition is not TRUE, it checks the condition again. If the condition is false, the loop is broken by the program.

For example, let us print the text “Hello, World!” 5 times.

Instead of typing print (“Hello World”) multiple times, a while loop will do the trick if you write it this way:

times = 1
while times <= 5:

    print ("Hello, World!")
    times += 1

Code explained: The loop runs as long as the times variable is less than or equal to 5. Then we set the last line to increase the times by 1 after each repetition.

Creating an infinite loop

This is when you create a while loop but the condition is always True and does not change. Since a while loop sets the program to run every time the condition is true, the while loop will continue repeating the loop till infinity.

i = 1
while i < 6:
  print(i)

If you type this code and run it, it will create an infinite loop where it continues to display i, that is 1 until the computer dies! That is because 1 will always be less than 6.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials