How to Run a Python Program Forever?

Challenge: Run a piece of Python code forever—until it is forcefully interrupted by the user.

Solution: use a while loop with a Boolean expression that always evaluates to True.

Examples: have a look at the following variants of an infinite while loop.

# Method 1: While Condition True
while True:
    # Your Python Code Here.
    # Example:
    print(42)

You can also use a while condition that always evaluates to True. For example, all integers or non-empty lists will evaluate to True:

# Method 2: While Condition evaluates to True
while 3421:
    # Your Python Code Here.
    # Example:
    print(42)

You can inverse a while condition that evaluates to False. For example, the following code waits a fixed number of milliseconds before running the next iteration:

# Method 3: Pause between loop iterations to save CPU
import time

while not time.sleep(5):
    # Your Python Code Here.
    # Example:
    print(42)   

The expression not time.sleep(5) always evaluates to True because the time.sleep() function returns None which evaluates to False.

You can actually try running the following code—or even implement your own loop body here: