Menu Close

How to kill a while loop with a keystroke in Python?

Sometimes, we want to kill a while loop with a keystroke in Python.

In this article, we’ll look at how to kill a while loop with a keystroke in Python.

How to kill a while loop with a keystroke in Python?

To kill a while loop with a keystroke in Python, we can catch the KeyboardInterrupt exception.

For instance, we write

try:
    while True:
        do_something()
except KeyboardInterrupt:
    pass

to add a infinite while loop into the try block.

And we catch the KeyboardInterrupt exception in the except block, which is triggered by pressing ctrl+c.

Conclusion

To kill a while loop with a keystroke in Python, we can catch the KeyboardInterrupt exception.

Posted in Python, Python Answers