While Loop in Python

The while loop in Python is used to execute a piece of code infinitely many times till a specific condition is satisfied. When the condition becomes false, the line immediately after the loops is executed.

For example-

x=0

while x<5:
  print(x)
  x+=1

print("x is no longer lesser than 5.")

The output-

0
1
2
3
4
x is no longer lesser than 5

Here, the interpreter stops executing the code located inside the while loop and moves on to the line immediately after the loop, which here is, print("x is no longer lesser than 5.").

The break statement

The break statement is used to stop a while loop even when the condition is true.

For example-

x=2

while x<6:
  if x==4:
    break
  else:
    print(x)
    x+=1

The output-

2
3

Here, the while loop stops when the value of x is 4 and doesn’t execute further. The True keyword, which is actually a boolean value, is also used with while loops. It is used in the form of while True:, and is generally followed by an if-else statement.

For example-

x=50

while True:
  if x<55:
    print(x)
    x+=1
  else:
    break

The output-

50
51
52
53
54

Here, the interpreter checks if x<55. If it is, it prints the value of x and adds 1 to it. It keeps doing this till x<55 is no longer true, and then moves on to the next code block (after the while loop).

The continue statement can be used in the same way as with for loops.

Infinite loops

A loop that continues on forever is called an infinite loop. As silly as the idea sounds, it actually has a bunch of real world applications like in game development and networking.

Let's see how to create one-

while True:
  print("Hi")

The output-

Hi
Hi
Hi
Hi
(goes on till you terminate the execution.)


That is all for today. Follow for more content on Python and programming.

Happy coding,
Aarav Iyer

Aarav Iyer

I am a technology and programming enthusiast, currently a high school student. I love drawing and am quite interested in aeronautics and astrophysics too. My favourite pastimes are reading books, blogging and skywatching with my telescope.

Post a Comment

Next Post Previous Post