Skip to content

RESOURCES / BLOG

How Do You End a Program in Python?

Hey folks,

I’m working on a Python script and need a way to end the program early based on a condition. Like, if a user gives the wrong input or something fails, I want the program to stop running without errors.

What’s the correct way to end a Python program? Are there different methods for doing it properly?

Thanks in advance!

Great question! Knowing how to end a Python program the right way is crucial, especially when handling errors, validating inputs, or building larger applications.

Let’s walk through the different ways you can stop or exit a Python script, along with practical examples. We’ll even throw in an example from an image-processing context to show how you’d do this in a real-world project.

Python provides several built-in ways to end your script.

These are the most beginner-friendly. They’re essentially the same and work fine in interactive mode (like in the Python REPL or Jupyter Notebook):

print("Program starting...")

exit()

print("This will not run.")Code language: PHP (php)

But they’re not ideal for production code because they’re meant for interactive use.

If you’re writing a real script or application, you should use sys.exit():

import sys

print("Checking user input...")

user_input = input("Type 'yes' to continue: ")

if user_input.lower() != "yes":

    print("Exiting program.")

    sys.exit()

print("Continuing the program...")Code language: PHP (php)

This is cleaner and works consistently across all environments.

Let’s say you’re trying to open an image file for processing:

import sys

import os

filename = "photo.jpg"

if not os.path.exists(filename):

    print(f"File '{filename}' not found. Ending program.")

    sys.exit()

print("File found. Continuing with processing...")Code language: PHP (php)

This is exactly how you’d handle errors before uploading or transforming images in a tool like Cloudinary.

You can also use exceptions to halt execution:

raise Exception("Something went wrong. Ending program.")

This will stop the program immediately and print a traceback. Use this if you want to signal a serious error.

Let’s say you’re checking image metadata:

import sys

def process_image(info):

    if "format" not in info:

        print("Missing image format. Exiting.")

        sys.exit()

    print("Processing image in format:", info["format"])

metadata = {"filename": "image.png"# Missing 'format'

process_image(metadata)Code language: PHP (php)

You might want to end a loop and the whole program at once:

import sys

while True:

    user_input = input("Enter command (or 'quit'): ")

    if user_input == "quit":

        print("Goodbye!")

        sys.exit()Code language: PHP (php)

This is common in CLI tools, command-based games, or interactive image upload scripts.

If you want your Python script to end, don’t rely on a crash or unhandled error:

# Bad practice!

some_var = None

print(some_var.upper())  # Will crashCode language: PHP (php)

Instead, check conditions and end gracefully:

if some_var is None:

    print("No data to process. Exiting.")

    sys.exit()Code language: PHP (php)

You can pass an exit code to signal why the program ended. This is useful in automation or CI/CD scripts.

import sys

sys.exit(0# 0 = success

sys.exit(1# 1 = errorCode language: PHP (php)

Other tools (like shell scripts or cron jobs) can read this code.

import sys

import os

def upload_image(file_path):

    if not os.path.exists(file_path):

        print("Image not found.")

        sys.exit(1)

    if not file_path.endswith((".png", ".jpg", ".jpeg")):

        print("Unsupported format.")

        sys.exit(1)

    print(f"Uploading {file_path} to Cloudinary...")

    # Simulate upload here

    print("Upload successful!")

upload_image("test.gif")Code language: PHP (php)

If your program opens files or connections, make sure to close them before exiting.

try:

    f = open("image.jpg", "rb")

    # Do something with the file

    raise Exception("Some problem")

except Exception as e:

    print("Error:", e)

finally:

    f.close()

    print("File closed. Exiting.")Code language: PHP (php)
MethodUse CaseRecommended
exit() / quit()Quick scripts or REPL sessions❌ Not for production
sys.exit()Clean exit with optional status code✅ Yes
raise Exception()Trigger errors explicitly✅ When needed
End of scriptJust let code run to the end✅ Normal behavior

Whether you’re validating input, handling file errors, or breaking out of an infinite loop, knowing how to end a Python program correctly keeps your code clean, professional, and user-friendly. In production code (like image pipelines, API endpoints, or CLI tools), always use sys.exit() to ensure a proper and predictable shutdown.

Start Using Cloudinary

Sign up for our free plan and start creating stunning visual experiences in minutes.

Sign Up for Free