How To Exit Python

In this tutorial, we will learn various ways on how to exit a Python script or a Python shell (like IDLE or a terminal) gracefully. Exiting Python is an important task, especially when you have finished running your code or working in the interpreter and need to close the program properly. Let’s dive in to explore the different ways to exit Python.

Method 1: Using exit() or sys.exit()

Using the exit() function or sys.exit() method is a standard way to close a Python script. Both exit() and sys.exit() are available in the sys module, which needs to be imported first.

To use exit() or sys.exit() in a Python script, follow these steps:

  1. Import the sys module with the command: import sys.
  2. Place the sys.exit() or exit() function where you want to exit the script.

Example:

Output:

Hello, World!

As you can see, the script terminated gracefully after printing “Hello, World!” using sys.exit().

Method 2: Using quit() or os._exit()

You can also use the quit() function or os._exit() method to exit Python. The quit() function is similar to exit() and os._exit() comes from the os module that also has to be imported first.

To use quit() or os._exit(), follow these steps:

  1. Import the os module with the command: import os.
  2. Place the quit() or os._exit() function where you want to exit the script.

Example:

Output:

Hello, World!

Again, the script terminated gracefully after printing “Hello, World!” using the quit() function.

Method 3: Exiting the Python Shell

If you’re using the Python shell (IDLE or terminal), you can exit by using the following commands:

  1. Type exit() or quit() and press Enter.
  2. Press Ctrl + Z in Windows or Ctrl + D in Linux/Mac to exit the Python shell.

If you’re using IDLE, you can also exit by clicking the X button at the top right of the shell window or by clicking File and selecting Exit.

Conclusion

In this tutorial, we’ve explored three different methods for exiting Python: using exit() or sys.exit(), using quit() or os._exit(), and exiting the Python shell. Now you know how to exit a Python script or shell gracefully, ensuring your programs terminate as intended.