While Loop

What is  a loop?

Loops are used in programming execute  block of code repeatedly.

What is while loop?

The while loop is used to iterate  a block of code until a condition  is true.

Syntax of while Loop

while (condition ):

    statement(s)

 

How the while Loop  works?

 The  while loop, first test the condition

 If  the condition is true,  it executes the block, it is called iteration

 After one iteration, the condition  is checked again. This  continues until the condition becomes false.

The  while loop is determined through indentation.

While the block  starts with an indented line of code and the first unindented line  of code has marked the end.

Flowchart of while Loop

flow chart while loop

Flowchart for while loop in Python

Example: While Loop using counter

The loop with counter allows to iterate the loop  define numbers of  times.

# Program to print numbers up to  n

n = int(input("Enter n: "))

# initialize the counter

counter = 1

while counter <= n:

          print(counter)

    counter += 1    # update the counter

Output

Enter n: 5

1

2

3

4

5

Explanation

In the above program, the condition counter =1 is True, it enters the while block.

It prints the value counter  and increment the counter, and check the condition until it is true and print the counter, once the counter is  6, condition becomes False and the loop is terminated.

Caution with a while loop

In the case counter loops it is important to note that counter variable must to increment or decrement, failing to do so leads to an infinite loop, since condition remains True forever.

While loop with else

While loops  can have an optional else block. The else part is executed when the condition evaluates to False.

Here is an example to illustrate this.

number = int(input("Enter number: "))

counter = 1

sum = 0

while counter <= number:

    sum = sum + counter

    counter = counter + 1

else:

            print("The sum is ", sum)

 

Output

Enter number: 10

The sum is  55

Infinite  loop

Infinite loop is a loop where condition always remains true. Few examples of infinite loops are:

while (1):

    statement

 while (True):

    statement

Sentinel-Controlled loops

Sentinel-controlled loops are sometimes called indefinite repetition because it is not known in advance how many times the loop will execute. These kind of loop uses using a sentinel value (also called  a flag value) to indicate "end of loop". The break statement is used along with some the condition for example.

counter = 1

while ( True) :

           if ( counter == 5):

                        print("Exiting from the loop")

                        break

          print("Sentinel-Controlled loops ", counter)

   counter+=1

​​​​​​​Output

Sentinel-Controlled loops  1

Sentinel-Controlled loops  2

Sentinel-Controlled loops  3

Sentinel-Controlled loops  4

Exiting from the loop