Welcome to this article of While Loop in Python, In this article we will see a detailed explanation of while Loop in Python with the help of some most important examples, so without wasting time. Let’s get start,
Before begin with while Loop, first we have to carry out the previous article of Loop, so, “Loop is a block of code, that’s used to execute without repeating the same code for multiple lines“.
As like the other programming languages, python also have some type of loops, and the most common between that is while that we will discuss in this article.
What is while Loop ?
“With the help of while loop, we can execute a block of code until the condition becomes false”. Means if we want to excute something for 100 Times, then we have to simply put certain condition then it will execute and after that condition become false, it will stop execution.
Syntax
while condition :
#body of the block
Flowchart
Example No. 1 : Program to display Number from 1 to 10
# program to display numbers from 1 to 10
i = 1 # Variable initialization
n = 10 # Variable initialization
# while loop from i = 1 to 10
while i <= n:
print(i)
i = i + 1
Output
1
2
3
4
5
6
7
8
9
10
Explanation
Step 1 :- Assigned two variable i as 1 and n as 10.
Step 2 :- Taken while loop with the condition i<=n i.e., 1<=10 condition is true, Then it will print value of i that is 1 Now.
Step 3 :- Next i=i+1, Means value of i is increamented by 1 i.e., i=2.
Step 4 :- Again it will go for while and check the condition, and it will execute untill the condition become false.
We can use While Loop Along with the Control Flow statements (Continue, Pass & Break) As well as Conditional Statements (If, If-Else etc).
Hope, after going through the whole article of while loop, you will came to know some basics about while loop.
For more concepts of Python, Kindly visit Python .
In case of any query, Please feel free to contact us.
Kindly share it with your friends.
Regards, EduPaat Team.