Skip to content

While true Python | while loop is bad? Break Out

  • by

Python While True creates an infinite loop and in other languages that use while

While true Python bad break

The base structure of that loop in Python:

While "condition" :

Flow

Python while loop is a conditional statement that runs as long as an expression evaluates to true. If while loop expression always evaluates to true. Therefore, the while loop will run every time.

Example

It makes an infinite loop that only exits when you expressly break the loop. For example:-

i = 0
while True:
    i += 1
    if i == 5:
        break
    print(i)

Output:

1
2
3
4

Note: If condition is true, It gonna create an infinite loop.

Q: In Python, is “while True:” a bad coding style?

Answer: That’s very debatable, while (true) is not a good idea because it makes it hard to maintain this code.

But that’s not bad since you may not always know the exit condition when you set up the loop or may have multiple exit conditions. However, it does require more care to prevent an infinite loop.

Q: What does “while True” mean in Python?

Answer: While True is True means loop forever.

The while loop will run as long as the conditional expression evaluates to True.

Since True always evaluates to True, the loop will run indefinitely, until something within the loop returns or breaks.

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in PyCharm 2020.1 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.4
Python 3.7
All Python Programs code are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *