While loop
In Python, while loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when then condition is become false, the line immediately after the loop in program is executed.It is also known as a pre-tested loop.
we use while loop when we do not know the number of iterate.
Syntax
While expression:
statement(s)
# All the statements indented by the same number of character spaces
Flow Chart
Working
a. The program first evaluates the while loop condition.
b. If it is true, then the program enters the loop and execute the body of the while loop.
c. It continues to execute the body of the while loop as long as the condition is true.2`
d. When it is false, the program comes out of the loop and stops repeating the body of the while loop.
Example 1 :
count=0
while(count<3):
count=count+1
print("python")
Output :
python
python
python
Example 2 : Program to print 1 to 10 using while loop
i=1
# The while loop will be iterate until condition become false.
while(i<=10):
print(i)
i=i+1
Output :
1
2
3
4
5
6
7
8
9
10
Infinite while loop
If the condition is given in the while loop never becomes false, then the while loop will never terminate, and it turns into the infinite while loop.
Any non-zero value in the while loop indicates an always-true condition, whereas zero indicates the always-false condition. This type of approach is useful if we want our program to run continuously in the loop without any disturbance.
Example :
while(1):
print("hi! we are inside the while loop")
Output :
hi! we are inside the while loop
hi! we are inside the while loop
--------
---------
Note : It is suggested not to use this type of loops as it is never ending infinite loop where the condition is always true and you have to forcefully terminate the compiler.
Note : Just like the if block, if the while block consists of a single statement when we can declare the entire loop in a single line.
Example
count=0
while(count==0): print("hello python")
Using else statement with while loop
The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it want be executed.
Syntax
while condition:
statement(s)
else:
statement(s)
Example
count=0
while(count<3):
count=count+1
print("python")
else:
print("hello")
No comments:
Post a Comment