While Loop in Python

Loops are used in Python to execute a statement according to their requirements. Python has followings types of loops -

  • while loop
  • for loop


Control Statements in Loops:
Control statements helps to change execution of loops from its normal sequence. There are three control statements - break, continue, pass.


while loop:
In Python while loop executes the code when the expression is evaluate to true.

Flowchart

Syntax:

while expression:
    code to be executed

Example:
i=1
while i<5:
    print(i)
    i +=1

Output will be

1
2
3
4


Control Statements in while loop:
The break statement is used to terminate the execution of the loops

Example:

i=1
while i<10:
    print(i)
    i +=2
    if i==5:
        break

Output will be
1
3


The continue statement is used to stop the current iteration, and continue with the next.

Example:

i=0
while i<10:
    i +=1
    if i==5:
        continue
    print(i)

Output will be
1
2
3
4
6
7
8
9
10

 

The pass statement is used as a null operation.
Example:

i=0
while i<10:
    i +=1
    if i==5:
        pass
    print(i)

Output will be
1
2
3
4
5
6
7
8
9
10

0 Comments

Newest