While Loop with Examples

Python: While Loop with Examples

While Loops are used in Python to execute a set of statements over and over until a condition is met.. When the condition is met, the line immediately following the loop in the programme is executed. Indefinite iteration is demonstrated by the while loop. The term “indefinite iteration” refers to the fact that the number of times the loop is executed is not specified explicitly in advance.

While Loop in Python

1)Syntax:

while expression:
    statement(s)

2)Working of while loop

After a programming construct, all statements indented by the same number of character spaces are considered to be part of a single block of code.. Python’s method of grouping statements is indentation. When a while loop is run, expression is evaluated in a Boolean context and, if true, the loop body is executed. The expression is then checked again, and if it is still true, the body is executed again, and so on until the expression becomes false.

Using while loop to print first n natural numbers. let us take n=15

Below is the implementation: 

# using while loop to print natural numbers upto n
n = 15
# let us take a temp variable to 1 as natural numbers starts from 1
temp = 1
# using while loop
while(temp <= n):
    # printing temp variable
    print(temp)
    # increment the temp by 1
    temp = temp+1

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

4)Multiple conditions in while loop

In a while statement, we can have multiple conditions, and we can use ‘and’ and ‘or’ with these conditions.

Below is the implementation: 

# using while loop to print even natural numbers upto n
n = 15
# let us take a temp variable to 2 as natural numbers starts from 2
temp = 2
# using while loop
while(temp <= n and temp % 2 == 0):
    # printing temp variable
    print(temp)
    # increment the temp by 2
    temp = temp+2

Output:

2
4
6
8
10
12
14

5)While loop with else

In Python, we can have while…else blocks similar to if…else blocks, i.e., an else block after a while block.

The while loop will execute statements from the white suite multiple times until the condition is evaluated as False. When the condition in the while statement evaluates to False, control moves to the else block, where all of the statements in the else suite are executed.

Ex: Printing first n natural numbers and printing 0 at last.

Below is the implementation: 

# using while loop to print natural numbers upto n
n = 10
# let us take a temp variable to 1 as natural numbers starts from 1
temp = 1
# using while loop
while(temp <= n):
    # printing temp variable
    print(temp)
    # increment the temp by 1
    temp = temp+1
else:
    print(0)

Output:

1
2
3
4
5
6
7
8
9
10
0

Related Programs: