Tutorial

Here is how to end a Program in Python

7 min read

In Python programming, knowing how to properly terminate a program is essential for writing robust and maintainable code.

Whether you need to exit a program due to an error, user intervention, or simply because the task is complete. Python provides multiple ways to end a program.

This article will explore five different ways on how to end a program in Python. It with detailed explanations and code examples for each approach.

So, let’s begin.

How to End a program in Python?

Different situations may require different methods for terminating a program, and Python provides several options to do so.

This section will explore various ways to end a Python program, including raising exceptions, using built-in functions, and handling user interrupts.

We will cover the following methods:

  1. Exiting with sys.exit(): A function that raises the SystemExit exception to terminate the program.
  2. Using quit() or exit(): Built-in functions that immediately stop program execution.
  3. Ctrl + C (Keyboard Interrupt): A way to forcefully terminate a running program from the terminal.
  4. Raising an Exception: Explicitly raising an exception to halt execution.
  5. End of Script Execution: Naturally reaching the end of your script to stop execution.

By the end of this guide, you’ll have a comprehensive understanding of how to effectively end a Python program in various contexts.

End a program in Python using sys.exit()

The sys.exit() function is one of the most common ways to terminate a Python program.

It raises the SystemExit exception, which can be caught in the code if needed, but generally, it effectively terminates the program.

This method is particularly useful when you want to exit a program due to a specific condition or an error.

Let’s consider a scenario where we want to terminate a program after checking a specific condition:

import sys

def check_condition(value):
    if value < 0:
        print("Negative value encountered. Exiting the program.")
        sys.exit()
    else:
        print(f"Value is {value}. Continuing execution.")

try:
    print("Starting the program...")
    check_condition(10)
    print("This will be printed because the value is positive.")
    check_condition(-5)
    print("This will not be printed because the program exits.")
except:
    pass

Output:How to end a program in Python? The image is an output for exit script using sys.exit() function

In this example, we have a function check_condition() that takes a value as input.

If the value is negative, it prints a message and calls sys.exit(), which raises the SystemExit exception and terminates the program.

If the value is positive, it prints a message and continues execution.

  • The first call to check_condition(10) passes a positive value, so the program prints the corresponding message and continues.
  • The second call to check_condition(-5) passes a negative value, so the program prints the exit message and terminates immediately.

Using sys.exit(), you can gracefully terminate a program when certain conditions are met, providing clear exit points and messages for better readability and debugging.

Terminate a Python program using exit() function

The exit() function is a built-in way to end a Python program immediately.

It is more commonly used in interactive sessions or simple scripts, providing a straightforward way to stop execution without needing to import any modules.

Here’s a simple example demonstrating the use of exit():

def greet_user(name):
    if not name:
        print("No name provided. Exiting the program.")
        exit()
    else:
        print(f"Hello, {name}!")

print("Starting the program...")
greet_user("Alice")
print("This will be printed because a name was provided.")
greet_user("")
print("This will not be printed because the program exits.")

Output:

output shows use of function exit() to terminate a python program

In this example, we have a function greet_user() that takes a name as input.

If the name is not provided (i.e., an empty string is passed), it prints a message and calls exit(), which immediately terminates the program.

If a name is provided, it prints a greeting message and continues execution.

  • The first call to greet_user("Alice") passes a valid name, so the program prints the greeting and continues.
  • The second call to greet_user("") passes an empty string, so the program prints the exit message and terminates immediately.

Using exit(), you can easily stop a program when certain conditions are met, especially in interactive or simple script scenarios.

Use Ctrl + C (Keyboard Interrupt) to end a Python program

Pressing Ctrl + C in the terminal sends a KeyboardInterrupt signal to the already running program, forcefully ending it.

This method is particularly useful for stopping long-running scripts or terminating programs in a development or debugging phase.

Consider a script that runs an infinite loop:

import time

print("Starting the program. Press Ctrl + C to terminate.")

try:
    while True:
        print("Running... Press Ctrl + C to stop.")
        time.sleep(2)
except KeyboardInterrupt:
    print("Program terminated by user.")

Output:

When running the script, you’ll see repeated messages until you press Ctrl + C:

Output of exit a Python program by pressing Ctrl+C

In this example, the script runs an infinite loop, printing a message every 2 seconds.

When you press Ctrl + C, a KeyboardInterrupt is raised, which is caught by the except block, printing a termination message.

  • The while True loop continues indefinitely until the user intervenes.
  • Pressing Ctrl + C raises a KeyboardInterrupt, which stops the loop and prints the termination message.

Using Ctrl + C is a simple and effective way to stop a running program, especially during development or testing, allowing you to quickly terminate execution without modifying the code.

Note: If you are on a Mac, you need to use Cmd + C

End a Python program by raising an exception

Explicitly raising an exception can be an effective way to halt the execution of a program.

By raising an exception, you can signal that an error or unexpected condition has occurred, prompting the program to stop.

This method is particularly useful for handling error cases and ensuring that your program exits gracefully when an issue arises.

Let’s consider a scenario where a function raises an exception when an invalid value is provided:

def check_value(value):
    if value < 0:
        raise ValueError("Negative value encountered. Terminating the program.")
    else:
        print(f"Value is {value}. Continuing execution.")

print("Starting the program...")
check_value(10)
print("This will be printed because the value is positive.")
check_value(-5)
print("This will not be printed because the program raises an exception.")

Output:

Output of ending a python program using by raising an exception

In this example, we have a function check_value() that takes a value as input.

If the value is negative, it raises a ValueError with a custom error message, effectively terminating the program.

If the value is positive, it prints a message and continues execution.

  • The first call to check_value(10) passes a positive value, so the program prints the corresponding message and continues.
  • The second call to check_value(-5) passes a negative value, raising a ValueError and terminating the program with a traceback message.

By raising an exception, you can clearly indicate when an error condition has been met, allowing the program to stop and provide helpful debugging information.

Wait for the Python script to end

In many cases, the simplest way to end a program in Python is to allow it to run to completion.

When the script reaches the end of its code, it naturally stops executing.

This is the default behavior and does not require any special functions or handling.

Consider the following simple script:

print("Starting the program...")
print("Performing some operations...")
print("Program completed successfully. Exiting.")

In this example, the program runs a series of print statements and then reaches the end of the script, naturally terminating.

There is no need for any special exit functions or exception handling, as the program stops when there is no more code to execute.

  • The script starts by printing a message indicating that the program has started.
  • It then performs some operations (in this case, printing messages).
  • Finally, it prints a completion message and ends execution.

Allowing a script to run to completion is often the most straightforward way to end a program, especially for simple tasks or scripts that do not require complex error handling or conditional exits.

Conclusion

In this article, we explored various way on how to end a Python program, including using sys.exit(), quit(), and exit(), handling Ctrl + C interruptions, raising exceptions, and naturally reaching the end of a script.

Each method serves different purposes and is suitable for different scenarios, whether you need to handle errors, stop execution based on specific conditions, or simply end the program gracefully.