Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

While Loop in Python

while loop in python

While Loop

While loop is entry control loop.Disadvantage of “For” loop is we cannot use condition in the loop. In python , if we need a loop which works on condition then we go with while loop. Also if we need an infinite loop we can use while loop.

Syntax of While loop

while(condition):
        #statements

Syntax for infinite loop

while(True):
        #statements
          (or)
while(1):
        #statements

Working 

  • Step 1: Take while loop with a condition
  • Step 2:  Evaluate expression in Boolean form
  • Step 3: If  boolean condition is True then it go inside the loop , if boolean condition is False then it terminates the loop
  • Step 4: It execute the statements inside the loop 
  • Step 5: Step 3 is repeated until the condition becomes False.

Python Code:

a=1
b=10
#loop with True condition
while(a<=b):
    print(a,end=” “)
    a+=1  #for incrementing a
print(\nValues at the point of terminating loop are : a={} and b={}.format(a,b))

Output:

1 2 3 4 5 6 7 8 9 10
Values at the point of terminating loop are : a=11 and b=10

Nested While loop

#printing a box pattern using nested while loop
i,n=0,5
while(i<n):
    j=0
    while(j<n):
        print(“*”,end=” “)
        j+=1
    i+=1
    print()

Output:

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *