While Loop in Python

While Loop in Python

While loop is one of the two major loops available in Python which are for loop and while loop. Loops in any programming language are used when a certain set of instructions are to be executed more than once in the program. Using loops in the programs make it short and simple. The while loop is used to execute a number of statements repeatedly until a given condition is true. It can be considered as a repeating if statement. It is used in situations where number of iterations is not known beforehand.

Syntax of While loop in Python:

while condition:
  statements

Flow Diagram of While loop:

while-loop

Example of While loop:

# Python program to exemplify use of while loop
sum = 0
n = 1
# Loop to find sum of first 10 natural numbers
while (n < 11):
  sum = sum + n
  n += 1
print(sum)

The program provided above prints sum of first ten natural numbers. It makes use of a variable named “sum” which will store the result and a variable named “n” which will be incremented until it reaches 11. When it becomes 11, while condition will no longer be true and loop will be exhausted. Sum will be then printed to the console. 

Output:

55

 

 

While Loop with Else statement in Python

Python provides a different type of while loop with else statement. It is executed when the condition of the loop evaluates to false.

Syntax of While loop with Else Statement in Python:

while condition:
  statements
else:
  statements

Example of While loop with Else Statement:

# Python program to exemplify use of while loop with else statement
num = 1
# Prints 1 to 10
while (num < 11):
  print(num)
  num += 1
else:
  print('loop exhausted.')

The program provided above prints numbers from 1 to 10 and when the while loop condition becomes false, else statement is executed which a single statement for the program provided above. It makes use of a variable named “num” which is initialized to 1. It is incremented by 1 in every iteration and printed to the console. When it becomes 11, the loop condition becomes false, and program control then goes to the else of while loop. It prints a single statement specifying that loop has finished executing.

Output:

1
2
3
4
5
6
7
8
9
10
loop exhausted.

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *