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 greater 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

You can create an infinite loop using while. This means that the loop keeps going on forever.

Personally, I find it quite fun to do so.

Lets see how to do it-

while True:
print("Hi")

The output-

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

That is all about the while loop in Python. Follow me for more such content on Python.

Follow this blog for more info on Python and coding!

Happy Coding,

Aarav Iyer

Aarav Iyer

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

Post a Comment

Previous Post Next Post