While Loops provides a way to code general loops in any programming language. A while loop is typically used to repeatedly execute a block of code until the given condition becomes False. In this article, I will present a tutorial on while loops in Python.
What are While Loops?
A While Loop has a condition as a boolean expression that can be either True or False. It is like a bouncer at the party who asks everyone whether they have a ticket or not. If you are having a ticket, it means that the condition is True and you are allowed to the party. If you are not having a ticket, it means that the condition is False and you are not allowed to enter the party. In programming, if the loop condition is not true you will not get inside the loop.
While Loops in Python
Now let’s see how to work with while loops in Python. To use a while loop, it is important to make sure that the body of a while loop is doing something that could make the loop condition false. If your while loop has no condition that could make it false, it becomes an infinite loop. For example, just run the code mentioned below:
while True: print("CTRL+C to stop")
CTRL+C to stop CTRL+C to stop CTRL+C to stop CTRL+C to stop CTRL+C to stop CTRL+C to stop CTRL+C to stop CTRL+C to stop ......
This kind of code is nothing more than an infinite loop. It will continue to run until you exit the program or press CTRL + C. Now let’s see how to write a while loop in Python that has both conditions to make the loop true and false. Suppose we want to write a program to keep splitting the first character of a string until the string becomes empty to make the condition false. Here is how we can write a while loop for such a program using Python:
x = "aman" while x: print(x, end=" ") x = x[1:]
aman man an n
Also, Read – Python Projects with Source Code.
Summary
While loops provide a way to code general loops. A while loop is generally used to keep executing a block of code till the given condition becomes false. I hope you liked this article on a tutorial on while loops in Python. Feel free to ask your valuable questions in the comments section below.