Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *