What Is “while True” in Python?

Python provides the while loop in order to iterate over multiple items which can be a list or similar enumerable objects. But the while loop can be also used in different ways where one of them is while True: . In this tutorial, we explain what is the meaning of the “while True:” line and how to use it in different ways.

Infinite Loops with the “while True:” Statement

The while statement accepts statements where every iteration the result of the statement is used to jump to the next iteration. The True statement is a boolean value that makes the while statement run forever or infinitely. Because in every step the while statement gets a True which jumps to the next step.

while True:
   print("I run infinitely")

Break Infinite “while True” Loop

The “while True” statement is used to run the while loop in an infinite way. We can specify conditions in order to break this infinite loop. The if statement can be used to specify the condition and exit from the infinite loop with the break statement. In the following example, we will break the “while True” statement if the variable a is equal to the 3.

a=0

while True:
   print("I run infinitely")
   a++
   if a == 3:
      break

Leave a Comment