To end a while loop prematurely in Python, press
CTRL-C while your program is stuck in the loop. This will raise a
KeyboardInterrupt error that terminates the whole program. To avoid termination, enclose the while loop in a try/except block and catch the
You can see the idea in the following code snippet:
try: while True: pass # Do something except KeyboardInterrupt: pass # Do something. Program doesn't terminate after CTRL-C print('hello world')
The while loop runs forever unless you end it prematurely using the
CTRL-C hotkey. But if you do, it prints the string
'hello world' to the shell instead of terminating the whole program:
Let me show you how this works in the following GIF:
❓ Question: Why do programmers always mix up Halloween and Christmas?
❗ Answer: Because Oct 31 equals Dec 25.
(If you didn’t get this, read our articles on the
int() Python built-in functions!)
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.