Python while loop is of indefinite iteration type, which means the number of times a loop is going to execute is not defined well in advance. The while loop keeps on executing until the condition stays True. Unlike python for loop, while loop does not have incremental/decremental iterator. If the iteration is known in advance then choose for loop otherwise choose while loop.
In this article, you will learn in-depth about while loop in Python.
Table of Contents
- Why you need a while loop in Python
- Create a while loop in Python
- Else statement in while loop
- Infinite loop python
- Python while break
- Python while loop in one line
- Conclusion
- Quiz – Python while loop
Why do you need a while loop in Python
A while loop in python executes the code present in the loop’s body as long as the underline condition remains True. You will want to use while loop in all the situation where the number of execution is not known in prior. Let’s say you want to keep on printing the random numbers and loop should break only if the random number is equal to 1. In this scenario, you can’t use a for loop because you don’t know after how many iterations the number is going to be 1.
In the subsequent section, you will learn to create while loop program.
Create Python while loop
Python while loop can be created with the help of while keyword and followed by the expression/condition. A while loop checks the condition and if the condition is true or the expression results in True condition.
Syntax – while loop
while (condition):
Body of loop
while is the keyword followed by a conditional statement and ends with a colon (:). Body of the while loop is indented (4 space or 1 tab space), which guarantee that the indented part falls under the loop execution.
Note: If you don’t provide indentation then Python will throw an error.
Example – While loop in Python
A python program to print “valid” until the number is equal to 3. Start the program with 0
i = 0
while (i != 3):
print ("valid")
i = i+1
Output:
valid
valid
valid
In the above code, while loop will start with a value of 0 and every time the condition is checked whether the value of i is not equal to 3 or not. If the value of i is not equal to 3 then the expression evaluates to True and the body of the loop gets executed. In the body section, a print statement gets executed first and then i is incremented with 1.
You can find the use of While loop in many examples available at Python basic code section.
Again the loop will check the condition and do the remaining task until the condition evaluates to False (i.e when i is 3).
Control flow diagram of While loop
else statement in while loop
Else statement in while loop is optional and can be used to execute something after python while loop completes its execution. A typical example of using else statement in while loop is given below,
i = 5
while (i >= 3):
print ("Number is greater than 3")
i = i-1
else:
print ("Number is smaller than 3")
Output:
Number is greater than 3
Number is greater than 3
Number is greater than 3
Number is smaller than 3
Infinite loop python
A while loop can also become infinite if the condition stays True always. In such case, the loop keeps on executing and interpreter hangs down and it is practically not possible to pause the execution or exit the loop. An example of an infinite loop using while loop is given below (also known as Python while true).
while True:
print ("Inside the loop")
In this example, the loop will keep on executing as there is no such condition which is going to be False. In such cases, you can say this as an infinite loop.
However, you can use the keyboard shortcut to exit the loop in and stop the iteration process. On Windows OS, you can press Ctrl + C. This will create a keyboard interrupt and loop will stop executing.
Python while break
Similar to for loop and if-else statement, the break can also be applied to while loop. As you are already aware that break is used to achieve early exist from the conventional iteration of the loop.
The example given below shows how to implement the “break” in while loop.
i = 0
while i < 5:
print ("less than 5")
if i == 2:
break
i += 1
Output:
less than 5
less than 5
less than 5
In this example, the break will enforce to exit the loop as soon as i is equal to 2.
Python while loop in one line
As you have seen earlier about one-line statements in the if-else tutorial, you can also implement simple while loop in one line itself.
An example of while loop in one line is given below,
i = 3
while i < 6: print ("Less than 6")
However, you are not advised to use one line statement like this, as it goes into infinite execution mode and requires a keyboard interrupt to terminate the execution (CTRL+C).
Conclusion
After reading this article you must have gained detailed knowledge on while loop. You have learned to create and use while loop for in various scenarios, especially when the iteration count is unknown. You have learnt to use else statement with while loop. This tutorial also briefed you on how a while loop can execute infinitely and a method to stop the execution. You learned to use break keyword to exit early from a while loop in Python.
I am sure you would apply this knowledge in your project or activity. Please do practice on this and in case you have any issue put them in the comment section.
Keep Learning and Keep Growing !!