Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to end program in Python

Learning the Art of Graceful Exit: Ending Programs in Python

Understanding Program Termination

In our daily lives, we often start tasks that we need to finish—be it cooking, reading a book, or even a workout. In the world of programming, this concept holds true as well. Every program you start must have an endpoint, a moment when it stops executing. This is what we call program termination.

In Python, a program naturally terminates when Python interpreter has executed all the lines of code. But there are scenarios when you might want to end the program prematurely, maybe due to an error condition or if a certain condition is met. Python provides several ways to do this, which we'll explore in this post.

The Basic: quit(), exit(), sys.exit()

quit() and exit()

You can use the quit() or exit() functions to stop the execution of your Python program. Here's an example:

print("Hello, World!")
exit()
print("This line will never be printed.")

In this example, the program will terminate before it gets a chance to print "This line will never be printed."

But there's a catch. quit() and exit() functions are not meant for use in real programs, they are intended for use in the interactive interpreter shell. If you are writing a script or creating a larger Python program, it's better to use sys.exit() instead.

sys.exit()

The sys.exit() function allows you to terminate your program. It's a function in the sys module, which means you need to import the sys module before you can use it. Here's how it works:

import sys

print("Hello, World!")
sys.exit()
print("This line will never be printed.")

Like quit() and exit(), sys.exit() will stop the execution of the program before it gets a chance to print "This line will never be printed."

Ending a Program Based on Conditions

Remember our daily tasks analogy? Just like how you would stop reading a book if it's not good, you might want to stop your program if certain conditions are met. Let's see how to do this.

Using an if statement with sys.exit()

You can use an if statement to check a condition and then call sys.exit() if the condition is met. Here's an example:

import sys

user_input = input("Enter 'q' to quit: ")

if user_input == 'q':
    sys.exit("You chose to quit the program.")

In this program, if the user enters 'q', the program will end and print "You chose to quit the program."

Handling Errors Using Exceptions and sys.exit()

Sometimes, you might want to end your program when it encounters an error. You can do this by combining exceptions with sys.exit().

Here's an example:

import sys

try:
    user_input = int(input("Enter a number: "))
except ValueError:
    sys.exit("You did not enter a number.")

If you run this program and enter a non-number, it will end and print "You did not enter a number."

The Graceful Exit: finally

In Python, you can use the finally keyword to specify a block of code that will be executed no matter what, even if an error occurred or the program is ending.

This is like cleaning up before you leave a room. You might not be able to control when you have to leave, but you can make sure you leave the room tidy.

Here's how you can use finally:

try:
    user_input = int(input("Enter a number: "))
except ValueError:
    sys.exit("You did not enter a number.")
finally:
    print("This is the end of the program.")

In this script, "This is the end of the program." will be printed no matter what. Even if you enter a non-number and the program ends, Python will still execute the finally block.

Conclusion: The Art of Ending Well

As you journey into the world of Python programming, remember that every beginning has an end. Whether it's a natural end, a conditional end, or an error-induced end, Python offers you a variety of ways to bring your program to a close.

So, just like a good story, make sure your Python program ends well. Because the end, after all, is just another form of beginning. In programming and in life, knowing how to end well is the first step to starting anew.