Python while loop

  • Python

In this article, we’ll learn about while loop in python. Returning a single statement multiple times manually is very difficult and you will need to write a single line of code multiple times like in the below example.

print("Techie Hours")
print("Techie Hours")
print("Techie Hours")
print("Techie Hours")

This is easy if you want to print only a few lines but what if you need to print the same text for like 20 times and writing the same piece of code will not be a good idea. While loop comes here for the rescue. Let’s check python’s while loop syntax

while condition:
  statement

Let’s understand this using the same example we discussed previously. We need to print Techie Hours 6 time using while loop.

Before we proceed with the example, you should know that we also require a counter for the while loop which you can also call as the Initialization parameter.

i = 1    # Counter

while i <= 6:    # Condition
  print("Techie Hours")
  i = i + 1    # Here we're increasing the counter by 1 every time while loop runs 

Output :

Techie Hours
Techie Hours
Techie Hours
Techie Hours
Techie Hours
Techie Hours

In the above example, the counter was set for 1 and we kept on increasing the counter by 1 each time our while loop executed. Once the value was greater than 6, it stopped as the condition was not met. Instead of incrementing the counter, we also can decrement the counter.

Nested while loop

We can use another while loop inside a while loop. Let’s check this with an example.

i = 1

while i <= 2:
  print("Techie")
  j = 1
  while j <= 2:
    print("Hours")
    j = j + 1
  i = i + 1

Output :

Techie
Hours
Hours
Techie
Hours
Hours

While loop with Else

We can also add an else statement with a while loop. Else statement will only run when the condition in while loop is False.

i = 1

while i <= 4:
  print("Inside while loop")
  i = i + 1
else:
  print("Outside while loop")

Output :

Inside while loop
Inside while loop
Inside while loop
Inside while loop
Outside while loop