Jump Links
Knowing how to end a program is important and can be handy in various scenarios. For instance, if you’re creating a simple game, you can quit on specific user input or when a certain condition is met. Discover the differences between the three ways of stopping a Python program.
1. Using quit() or exit()
One of the simplest ways of ending a Python program is to use either of the built-in methods, quit() or exit(). When you call either quit() or exit(), the program will terminate.
The quit() and exit() functions do exactly the same thing, it’s just a matter of personal preference which you use.
Here's how you can use the quit() function to end a Python program:
for num in range(10):
if num == 9:
quit()
print(num)
The sample program above will print integers from 0 to 8 on the console. Once num is 9, the program exits. You can also use the quit() command to exit the Python Integrated Development and Learning Environment (IDLE), which allows you to run Python scripts interactively.
Note that both quit() and exit() rely on the site module so you shouldn’t use them in production environments. The next method, sys.exit(), is a better option.
2. Using sys.exit()
When you call sys.exit() in your program, Python raises a SystemExit exception. It accepts an optional argument to specify an integer exit code (0 by default). You can also pass an object which will result in an exit code of 1 and will print the object’s string value to standard error.
import sys # Remember to include this statement at the top of the module
for num in range(10):
if num == 5:
sys.exit("You exited the program")
print(num)
The output of the program will be as follows:
Like the quit and exit methods, sys.exit() also raises a SystemExit exception. This means that you can call sys.exit() or raise SystemExit(). Both accept an optional argument.
You should learn about the most important Python functions if you don't understand how the code above works.
3. Using os._exit()
The third way of exiting a program is the special os._exit() method. You can pass it an optional argument to specify an exit status code. os._exit() comes from the os module and terminates the process immediately without performing the normal cleanup activities that occur when a Python program exits.
Because this function exits without performing normal cleanup, you should only use it in special instances. According to the Python documentation, a good example is in a child process after a fork (a new process created using os.fork()).
Here's an example of how to use the os._exit() function to end a program:
import os
import sys
def child_process():
print("Child process is running.")
os._exit(0)
def main():
print("Parent process is running.")
try:
pid = os.fork()
if pid == 0:
# Code in the child process
child_process()
else:
# Code in the parent process
print(f"Parent process is continuing with child process PID: {pid}")
except OSError as e:
print(f"Fork failed: {e}")
sys.exit(1)
print("Parent process is done.")
if __name__ == "__main__":
main()
The code above will output the following:
Which Method Should You Use to Terminate a Program in Python?
Python provides various methods to end a program. However, most of these methods do the same thing. This should reduce the burden of decision-making if you need to add an exit mechanism to your program when learning Python.
In summary, sys.exit() should be your go-to method for ending a program in Python. It raises a SystemExit exception with an optional exit code.
The quit() and exit() methods are more appropriate when using the Python REPL. You should avoid them in production because they depend on the site module, which may not always be available. You should rarely need to use os._exit(), unless you’re working with code that forks processes.