Python While loops

 

  • We use while loop when we dont know the exact count of iteration for a particular condition.

While Loop Syntax:

As long as a condition is true , we can execute a set of statements with while loop.

Syntax

while(condition):
     Statement(s)

 

01. Example

N=[10,20,30,40,50]
product=1
index=0

while index<len(N):
    product = product*N[index]
    index+=1
print("Product is:{}".format(product))

Output:

Product is:12000000

 

Note:If we forget to increment index, the loop will continue forever , which is also known as infinite loop.


While Loop With Else:

The else part is executed if the condition in while loop evaluates to False.

Example

N=[1,2,3]
index=0

while index<len(N):
    print(N[index])
    index+=1
else:
    print("No item left in list.")

Output:

1
2
3
No item left in list.

Break Statement With While:

The while loop can be terminated with break statement.

Example

iteration = 10
while iteration < 20:
    print(iteration)
    if iteration == 13:
        break
    iteration += 1

Output:

10
11
12
13

Continue Statement With While:

We can stop the current iteration and continue with the next using continue statement.

Example

iteration = 10
while iteration < 20:
    iteration += 1
    if iteration == 13:
        continue
    print(iteration)

Output:

11
12
14
15
16
17
18
19
20

While Loop As Single Line Statement:

Example

N = 4

while(N>0): N = N - 1; print(N)

Output:

3
2
1
0

While Loops Examples:

01. Example

N = int(input ("Enter A Number To Print Table:"))            
counter = 1
print ("The Table of: ", N)
while counter <= 10:
    print (N, 'x', counter, '=', N*counter)
    counter += 1

Output:

Enter A Number To Print Table:8
The Table of:  8
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
8 x 10 = 80

 

02. Example

N = int(input("Enter a number: "))
 
factorial = 1
counter = 1
 
while counter <= N:
    factorial = factorial * counter
    counter = counter + 1
 
print("Factorial of ", N, " is: ", factorial)

Output:

Enter a number: 8
Factorial of  8  is:  40320

 

03. Example

string = 'zeroones'
counter = 0

while counter < len(string):
  if string[counter] == 'o' or string[counter] == 'e':
    counter += 1
    continue
    
  print('Word :', string[counter])
  counter += 1

Output:

Word : z
Word : r
Word : n
Word : s

 

Leave a comment