KeyboardInterrupt in Python: Causes and Fixes with Simple Examples

 What is KeyboardInterrupt in Python?

A KeyboardInterrupt in Python occurs when the user manually stops a running program, usually by pressing Ctrl + C on the keyboard.

In simple words, Python is saying:

“The program was stopped by the user.”

This error is not caused by wrong code - it happens when a program runs too long or enters an infinite loop, and the user interrupts it.


When Does KeyboardInterrupt Occur?

KeyboardInterrupt commonly happens when:

  • A program runs too long

  • A program enters an infinite loop

  • A user presses Ctrl + C to stop execution

  • A script waits for input but gets interrupted


Common KeyboardInterrupt Error Message


KeyboardInterrupt

Example 1: Infinite Loop Causing KeyboardInterrupt

Incorrect Code


while True:
    print("Running...")

🔴 The program runs forever until you press Ctrl + C

Error


KeyboardInterrupt

Why this happens

The loop never ends, so the user stops it manually.


Example 2: Long-Running Program Interrupted

Code


import time

for i in range(10):
    time.sleep(2)
    print(i)
If you stop it early using Ctrl + C, Python raises:

KeyboardInterrupt

Example 3: KeyboardInterrupt During Input

Code


name = input("Enter your name: ")
If the user presses Ctrl + C before entering input:

KeyboardInterrupt

How to Handle KeyboardInterrupt Safely

You can catch KeyboardInterrupt using try–except to stop programs gracefully.

Correct Code


try:
    while True:
        print("Running...")
except KeyboardInterrupt:
    print("Program stopped safely!")

Example 4: Graceful Exit on KeyboardInterrupt

Code


try:
    for i in range(100):
        print(i)
except KeyboardInterrupt:
    print("Execution stopped by user.")

Why Handling KeyboardInterrupt is Useful

  • Prevents crash messages

  • Allows safe exit

  • Saves unfinished data

  • Improves user experience


How to Avoid KeyboardInterrupt Issues

✔ Avoid infinite loops
✔ Add loop exit conditions
✔ Use timeouts when needed
✔ Handle interrupts using try–except
✔ Keep programs responsive


Difference Between KeyboardInterrupt and Other Errors

Error TypeCause
KeyboardInterruptUser stops program
RuntimeErrorCode execution issue
SyntaxErrorCode writing mistake
ValueErrorWrong data type value

Summary

KeyboardInterrupt in Python occurs when a user manually stops program execution.
It is not a bug, but a control signal to stop running code safely.

Learning to handle it helps make your programs more stable and user-friendly.


Frequently Asked Questions (FAQ)

Q1: Is KeyboardInterrupt a real error?

It is an exception raised when the user stops the program.

Q2: Does KeyboardInterrupt mean my code is wrong?

No. It only means the user stopped execution.

Q3: Can I prevent KeyboardInterrupt?

You can handle it, but users can still stop programs.

Q4: Should I ignore KeyboardInterrupt?

No. Handle it gracefully in long-running programs.


📌 Final Tip

Always handle KeyboardInterrupt in programs that run for a long time.

Comments

Popular posts from this blog

AttributeError in Python: Causes and Fixes with Simple Examples

SyntaxError in Python: Causes and Fixes with Simple Examples

SystemExit in Python: Causes and Fixes with Simple Examples