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
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
# 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)
not time.sleep(5) always evaluates to
True because the
time.sleep() function returns
None which evaluates to
You can actually try running the following code—or even implement your own loop body here:
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.