How To Stop A Python Program

In this tutorial, we will discuss different ways to stop a Python program. Stopping a Python program can be crucial while debugging, when an error occurs, or when user input is required to proceed. We will cover methods like using keyboard interrupts, sys.exit(), and raising exceptions to achieve this goal.

Step 1: Using Keyboard Interrupts (Ctrl+C)

The simplest way to stop a Python program is by using the keyboard interrupt. This method works for both script-based and interactive terminal executions. To use your keyboard to interrupt the program, press Ctrl+C. It raises a KeyboardInterrupt exception, which stops the execution.

Here’s an example:

Output

Running...
Running...
Running...
Stopped by user

Press Ctrl+C to stop the program, and it will display “Stopped by user”.

Step 2: Using sys.exit()

A more direct way to stop a Python program is by using the sys.exit() function. This function allows you to exit a program with an optional exit code. The default exit code is 0, which indicates successful termination. You can import the sys module and use the exit() function as follows:

For instance, you can use sys.exit() to exit a program based on user input:

Output

Do you want to exit the program? (yes/no): yes
Exiting the program.

Entering “yes” when prompted will trigger the sys.exit() function and display “Exiting the program.”

Step 3: Raising Exceptions

Raising exceptions is another way to stop a Python program. Exceptions are events that can be triggered when an error occurs, or when a specific condition is met. Once an exception is raised, the program stops at that point unless the exception is caught and handled by a try-except block.

To raise an exception, use the raise keyword followed by the exception type.

Here’s an example:

For instance, you can raise an exception based on user input:

Output

Enter a positive number: -3
Traceback (most recent call last):
  File "stop_python.py", line 4, in 
    raise ValueError("Negative number entered. Exiting the program...")
ValueError: Negative number entered. Exiting the program...

Entering a negative number will raise a ValueError and display the associated message.

Conclusion

In this tutorial, we covered three ways to stop a Python program, using keyboard interrupts, the sys.exit() function, and raising exceptions. Depending on your requirements and program structure, you can choose the most appropriate method to stop your Python program correctly.