While loop in python

Share:

    

While loop👇:

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. We generally use this loop when we don't know the number of times to iterate beforehand.

Some programs of while loop:

Program 1:

#Prograam for print 1-5 numbers
#a=0 mean a start from 0
a = 0
# a is smaller then 10
while a < 10:
    print(a)
#if a is equal to 5 then break the loop
    if(a == 5):
        break
#At every exectution add 1 in a
    a += 1

Output:

0              
1
2
3
4
5

Program 2:

print("Print odd numbers in vertical position and even numbers in horizontal position")
i=0
n=1
print("odd numbers")
while (i<10):
print(i+1)
i=i+2
print("Even numbers")
while(n<10):
print(n+1,end=" ")
n=n+2                                                                                                                                                                            

Output:

Print odd numbers in vertical position and even numbers in horizontal position
odd numbers
1
3
5
7
9
Even numbers
2 4 6 8 10

Nested while loop in Python👇:

When a while loop is present inside another while loop then it is called nested while loop.

some program for nested while loop

Program 1:

i = 1                              
j = 5                              
while i < 4:                       
    while j < 8:                   
        print(i, ",", j)           
        j = j + 1                  
        i = i + 1                  

Output:

1 , 5
2 , 6
3 , 7

Program 2:

b=1
x=1
while b<=2:
    print('here is the outer loop\n')
    while x<=1:
        print('here is the inner loop\n')
        x=x+1
    b=b+1

Output:

here is the outer loop here is the inner loop here is the outer loop