How to Exit a Program in Python
What you'll build or solve
You'll stop a Python program on purpose, either after finishing work or when a condition fails.
When this approach works best
Exiting a program works well when you:
Learn Python on Mimo
- Stop early after validation fails, like missing config or bad input.
- End a CLI tool after printing help, version info, or an error message.
- Quit a loop-driven script after a user chooses an exit option.
Avoid forcing an exit inside reusable functions or libraries. Return values or raise a specific exception instead, then let the caller decide when to stop.
Prerequisites
- Python installed
- You know how to run a Python script
Step-by-step instructions
1) Let the program end naturally
A Python script ends when it reaches the end of the file. This is the cleanest "end" for most scripts.
Python
print("Start")
print("All done")
If you are inside a function, use return to end that function.
Python
def greet(name):
if not name:
return
print("Hi", name)
greet("")
print("Program continues")
What to look for:
return stops only the current function, not the whole program.
2) Exit early in scripts with sys.exit()
Use sys.exit() when you want to stop the whole program immediately. You can exit with a status code, which is useful for command-line tools and automation.
Python
import sys
config_ok = False
if not config_ok:
print("Missing config")
sys.exit(1)
print("This will not run")
Option A: Exit with success
Python
import sys
print("Finished successfully")
sys.exit(0)
Option B: Exit with a message
Passing a string prints it to the console and exits with a non-zero code.
Python
import sys
sys.exit("Invalid arguments")
What to look for:
sys.exit() is the reliable choice for scripts. exit() and quit() exist mainly for interactive sessions (the Python REPL) and can behave differently in scripts.
Also, sys.exit() raises a SystemExit exception. This matters if you catch broad exceptions and accidentally swallow the exit.
Examples you can copy
Example 1: Exit when required input is missing
Python
import sys
path = ""
if not path:
sys.exit("Missing --path")
Example 2: Exit with different status codes
Python
import sys
ok = True
if ok:
sys.exit(0)
else:
sys.exit(1)
Example 3: End a menu program when the user chooses "0"
Python
while True:
choice = input("Choose 1/2 or 0 to quit: ").strip()
if choice == "0":
break
if choice == "1":
print("Option 1")
elif choice == "2":
print("Option 2")
else:
print("Unknown option")
print("Bye")
Example 4: Stop inside a function, not the whole program
Python
def parse_age(text):
text = text.strip()
if not text.isdigit():
return None
return int(text)
age = parse_age("x")
print(age)
print("Program continues")
Example 5: Exit early after printing help
Python
import sys
args = ["--help"]
if "--help" in args:
print("Usage: tool.py [--help] [--version]")
sys.exit(0)
print("Run the tool")
Common mistakes and how to fix them
Mistake 1: Using return and expecting the whole program to stop
What you might do
Python
def main():
print("Stopping")
return
main()
print("Still running")
Why it breaks
return stops only the function. The program continues after the call.
Fix
Use sys.exit() when you need to end the program from the main script path.
Python
import sys
def main():
print("Stopping")
sys.exit(0)
main()
print("This will not run")
Mistake 2: Catching exceptions and preventing the program from exiting
What you might do
Python
import sys
try:
sys.exit(1)
except BaseException:
print("Still running")
Why it breaks
Catching BaseException also catches SystemExit, so the program does not exit.
Fix
Avoid except BaseException unless you have a strong reason. If you must catch it, re-raise SystemExit.
Python
import sys
try:
sys.exit(1)
except SystemExit:
raise
Troubleshooting
If your script "doesn't exit," look for except BaseException or a bare except: that catches SystemExit. Re-raise SystemExit.
If CI or a shell treats your run as failed, you exited with a non-zero status. Use sys.exit(0) for success.
If your program ends too early, search for sys.exit() calls that run on import. Keep exits inside main() or behind a condition.
If you want to stop only a function, use return instead of exiting the entire program.
If your exit message does not show up, print the message before exiting, or pass a string to sys.exit().
Quick recap
- Let scripts end naturally when possible.
- Use
returnto stop a function. - Use
sys.exit(code)to exit a program in scripts, with0for success and non-zero for errors. - Use
sys.exit("message")to exit with a message. - Prefer
sys.exit()overexit()andquit()in scripts.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot