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 KeyboardInterrupt.
You can see the idea in the following code snippet:
β₯οΈ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month
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:
hello world
Let me show you how this works in the following GIF:

Programmer Humor
β 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 oct() and int() Python built-in functions!)