While Loop: 3 Important Things You Should Know About
A While Loop is the most underrated and less frequently used looping statement in python. But if you intend to use while loop in python, Here are 3 Important things you should know about while loop in python and what are the difference between for loop and while loop.
What Is A While Loop?
To put it simply for your understanding a while loop is a persistent piece of code which never stops it’s execution until the condition of the while loop is proven to be FALSE.
In other words the while loop will be executed up-to the point where it can prove the condition given to the while loop is TRUE.
Here Is A Flowchart Illustrating How a While Loop Works
Example Program
i=0
while i<7:
print(i)
i+=1
Output:
0
1
2
3
4
5
6
In the above program the given condition (i < 7) will be TRUE until the variable i has the value 7.
When i = 7, it no longer satisfies the given condition which is (i<7) which turns the condition FALSE and stops the execution of the loop
1. Else Statement
When you are using the while loop you can still run the block of code even if the condition is FALSE with the help of the else statement.
Example Program
i = 1
while i < 7:
print(i)
i += 1
else:
print("i is no longer less than 7")
Output:
1
2
3
4
5
6
i is no longer less than 7
2. Continue Statement
With the help of the continue statement you can stop the current looping cycle(iteration) and continue with the next value.
Example Program
i = 0
while i < 7:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
6
3. Break Statement
By using the break statement you can stop the loop from execution, even if the condition is proved to be TRUE.
Example Program
i = 1
while i < 7:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3
The Difference Between For Loop And While Loop
For Loop | While Loop |
---|---|
For Loop's Syntax: for(initialization; condition; iteration){ //body of ‘for’ loop} | While Loop's Syntax: while (condition) { statements; //body of loop} |
For Loop will be executed for infinite amount of time if a condition not is given. | While Loop will not execute if a condition is not given. |
The condition in the for loop is initialized only once. | The condition in the While Loop is initialized on each and every iteration while checking if the condition is TRUE or FALSE |
While using the for loop you should be aware of the number of iteration needed for you to complete your code execution. | Whereas in the while loop you can execute the loop even if you are not aware of the number of iteration needed for you to complete your code execution. |
Reference Books
Here are the books I've used as reference for writing this article, Please feel free to read them If you don't want your knowledge to limited to this article alone.
Post a Comment