How To: Python infinite loops with while true

Here is a quick guide on how to create an infinite loop in python using a ‘while true’ statement. There are number of reason that you might want to implement this; a great use case would be outputting a fluctuating variable to the terminal such as a temperature reading from a sensor.

Python infinite loop - exitcode0
loops that make your brain hurt

A ‘while true’ statement allows us to run a sequence of code until a particular condition is met. In order to make that sequence of code run in an infinite loop, we can set the condition to be one that is impossible to reach. Better still, we can simply omit the condition altogether to ensure that the while true loop never ends.

while True:
        print("The current time is: %s" % strTimeNow)
        time.sleep(5)

In cases where it would be useful to exit that loop if a given condition is met or exception is reached, we can encase our ‘while true’ statement with a ‘try except’ statement.

try:
    while True:
        print("The current time is: %s" % strTimeNow)
        time.sleep(5)
except KeyboardInterrupt:
    print("Hard Exit Initiated. Goodbye!")

There are a number of exception that can be handled by a try statement, I have chose to use the KeyboardInterupt (Ctrl+C) clause in this example.

You can learn more about exception handling here: https://docs.python.org/3/tutorial/errors.html#handling-exceptions


More Python Tips and tricks:

One Reply to “How To: Python infinite loops with while true”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: