How to Exit a Python Program: Simple Methods Explained
To exit a Python program, use
exit(), quit(), or sys.exit(). The sys.exit() function is preferred in scripts and allows you to specify an exit status code.Syntax
Here are the common ways to exit a Python program:
exit(): Exits the interpreter, mainly for interactive use.quit(): Similar toexit(), also for interactive use.sys.exit([status]): Exits the program and optionally returns a status code to the operating system.
To use sys.exit(), you must first import the sys module.
python
import sys # exit() # Exit the program # quit() # Exit the program sys.exit(0) # Exit with status code 0 (success)
Example
This example shows how to exit a Python program using sys.exit() with a status code. The program prints a message, then exits.
python
import sys print("Program is running") sys.exit(0) print("This line will not run")
Output
Program is running
Common Pitfalls
Some common mistakes when exiting a Python program include:
- Using
exit()orquit()in scripts instead ofsys.exit(). The first two are meant for interactive use and may not work as expected in all environments. - Not importing the
sysmodule before callingsys.exit(). - Expecting code after
sys.exit()to run. Once called, the program stops immediately.
python
import sys # Wrong: Using exit() in a script (may not always work) # exit() # Right: Using sys.exit() with import sys.exit(1) # Exit with error status
Quick Reference
| Method | Description | Use Case |
|---|---|---|
| exit() | Exits interpreter | Interactive sessions |
| quit() | Exits interpreter | Interactive sessions |
| sys.exit([status]) | Exits program with status code | Scripts and programs |
Key Takeaways
Use sys.exit() to exit Python programs cleanly with an optional status code.
exit() and quit() are best for interactive use, not scripts.
Always import sys before calling sys.exit().
Code after sys.exit() will not run.
Use status codes to indicate success (0) or error (non-zero).