The while True Statement in Python

Muhammad Maisam Abbas Oct 10, 2023
The while True Statement in Python

This tutorial will discuss the while True statement in Python.

Define the while True Statement in Python

In Python, the True keyword is a boolean expression. It’s used as an alias for 1, and the while keyword is used to specify a loop. The statement while True is used to specify an infinite while loop.

An infinite loop runs indefinitely until the end of time or when the program is forcefully stopped. The following code example below shows us how we can create an infinite loop with the while True statement.

while True:
    print("Hello World")

Output:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

We created an infinite while loop that prints Hello World every time it is executed by using the while True statement in the code above. This approach is not recommended because it stops the code from its completion.

One workaround is the use of the break statement inside the infinite loop to stop the process when a particular condition is satisfied. This approach is demonstrated in the following program below.

i = 0
while True:
    print("Hello World")
    i += 1
    if i == 10:
        break

Output:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

We stopped the infinite while loop by using the break statement in the code above. The execution of the infinite loop was stopped after the value of the integer variable i becomes equal to 10.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Python Loop