While Loops in Python

In the previous lesson we have seen why loops are essential in programming languages, in this article we will explore a common type of loop present, that is the While loops in Python. While loop is a loop which first checks whether a particular condition matches, and then executes the statements which are embedded within the looping structure of the while statement. When the condition fails to match the loop simply quits and continues on to the next line of statement present in the Python code.

Syntax and Working of While Loops in Python

The typical structure of the while loops in Python are as follows:

while condition_test:
    Statement 1
    Statement 2
    Statement 3
     ....
Statements

We use the colon ( : ) to create the looping statement block, and then we use the indentation after for the various looping statements. The indentation is necessary. Let us look at an example program involving the while loop.

#An example program to print "Hello World" 5 times
i=0
while i<5:
    print("Hello World")
    i=i+1
Output:
Hello World
Hello World
Hello World
Hello World
Hello World

In the above program the variable ‘i’ acts as a counter which keeps track of how many times the looping structure is run. We initialize ‘i’ as zero, but then using the while condition specify that the loop should run only while i remains less than 5. Each time the loop executes while i is still below the value of 5, it prints out the text “Hello World” and then increases the count of the variable i. Finally, upon reaching the value of 5 the program is no longer executed.

Suppose the program specified the while loop to execute when True, like so:

#An example program to print "Hello World" 5 times
i=0
while True:
    print("Hello World")

It would result in an infinite loop with unlimited attempts to print “Hello World unless the Python execution is forced to quite or the program itself is terminated. Next let us look at combining loops together with user-provided input values.

#Prints the "Hello World" the number of times specified by the user
n=int(input("Enter a number :"))
i=0
while i<n:
    print("Hello World")
    i=i+1
Output:
Enter a number :7
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

We see that the program acts and prints according to the number specified during input. In the next article we will delve further into looping programs and take a look at the range( ) function.

Leave a Comment