Let me give some information on them:

  1. quit() simply raises the SystemExit exception.

Furthermore, if you print it, it will give a message:

    >>> print (quit)
    Use quit() or Ctrl-Z plus Return to exit
    >>>

This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.

Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.

  1. exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.

Furthermore, it too gives a message when printed:

    >>> print (exit)
    Use exit() or Ctrl-Z plus Return to exit
    >>>

However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.

  1. sys.exit() also raises the SystemExit exception. This means that it is the same as quit and exit in that respect.

Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.

  1. os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.

Note that, of the four methods given, only this one is unique in what it does.

Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.


Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:

raise SystemExit

This way, you do not need to import sys first.

However, this choice is simply one on style and is purely up to you.

Answer from user2555451 on Stack Overflow
Top answer
1 of 4
1006

Let me give some information on them:

  1. quit() simply raises the SystemExit exception.

Furthermore, if you print it, it will give a message:

    >>> print (quit)
    Use quit() or Ctrl-Z plus Return to exit
    >>>

This functionality was included to help people who do not know Python. After all, one of the most likely things a newbie will try to exit Python is typing in quit.

Nevertheless, quit should not be used in production code. This is because it only works if the site module is loaded. Instead, this function should only be used in the interpreter.

  1. exit() is an alias for quit (or vice-versa). They exist together simply to make Python more user-friendly.

Furthermore, it too gives a message when printed:

    >>> print (exit)
    Use exit() or Ctrl-Z plus Return to exit
    >>>

However, like quit, exit is considered bad to use in production code and should be reserved for use in the interpreter. This is because it too relies on the site module.

  1. sys.exit() also raises the SystemExit exception. This means that it is the same as quit and exit in that respect.

Unlike those two however, sys.exit is considered good to use in production code. This is because the sys module will always be there.

  1. os._exit() exits the program without calling cleanup handlers, flushing stdio buffers, etc. Thus, it is not a standard way to exit and should only be used in special cases. The most common of these is in the child process(es) created by os.fork.

Note that, of the four methods given, only this one is unique in what it does.

Summed up, all four methods exit the program. However, the first two are considered bad to use in production code and the last is a non-standard, dirty way that is only used in special scenarios. So, if you want to exit a program normally, go with the third method: sys.exit.


Or, even better in my opinion, you can just do directly what sys.exit does behind the scenes and run:

raise SystemExit

This way, you do not need to import sys first.

However, this choice is simply one on style and is purely up to you.

2 of 4
156

The functions* quit(), exit(), and sys.exit() function in the same way: they raise the SystemExit exception. So there is no real difference, except that sys.exit() is always available but exit() and quit() are only available if the site module is imported (docs).

The os._exit() function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork() call.

Conclusion

  • Use exit() or quit() in the REPL.

  • Use sys.exit() in scripts, or raise SystemExit() if you prefer.

  • Use os._exit() for child processes to exit after a call to os.fork().

All of these can be called without arguments, or you can specify the exit status, e.g., exit(1) or raise SystemExit(1) to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256) on many systems this will get truncated and your process will actually exit with status 0.

Footnotes

* Actually, quit() and exit() are callable instance objects, but I think it's okay to call them functions.

๐ŸŒ
Linux Hint
linuxhint.com โ€บ exit-from-python-program
How to Exit from the Python Program โ€“ Linux Hint
The KeyboardInterrupt and raise SystemExit statement can be used also to terminate the program. The uses of these built-in functions and the statement have been shown in this tutorial. The exit() function is the most common function of the Python to terminate from the script.
Discussions

Whats is the function of exit()?
Hello, Iโ€™m in the process of learning Python. And I have some questions that I do not completely understand after researching. What does the โ€œexit()โ€ function? Because if I run a basic program, it does not matter if I typed or not the โ€œexit()โ€ function. The program stops: More on discuss.python.org
๐ŸŒ discuss.python.org
5
0
August 28, 2021
Return vs sys.exit()
Consider a program with threads and lots of asynchronous stuff. I have a main where at the end of it somebody has written โ€œsys.exit(0)โ€. And in catching exceptions at some places thereโ€™s sys.exit(1). But I want to return some data at the end of main. If I use return statement above ... More on discuss.python.org
๐ŸŒ discuss.python.org
9
0
February 5, 2024
Exit a Python program, and Python, COMPLETELY.
The root.mainloop() function creates an infinite loop, which means that any statements following it will not be executed unless the loop is interrupted. To exit the loop, consider adding a 'Quit' button to your application and set its command to root.destroy. Once you click this button, the loop will hopefully terminate. More on reddit.com
๐ŸŒ r/learnpython
3
2
October 20, 2023
How to exit Python program if an if statement is true?
To directly answer your question: import sys # at top of file sys.exit() # where you want to exit You might also consider putting your code in functions and returning early / a special value if something breaks, or raising exceptions (particularly if it indicates a bug / misuse of your code /function by another function). More on reddit.com
๐ŸŒ r/learnpython
4
0
February 11, 2022
๐ŸŒ
Codecademy
codecademy.com โ€บ article โ€บ python-exit-commands-quit-exit-sys-exit-os-exit-and-keyboard-shortcuts
Python Exit Commands: quit(), exit(), sys.exit(), os._exit() and Keyboard Shortcuts | Codecademy
It demonstrates how quit() halts execution in an interactive Python environment. Similar to quit(), Python offers exit(), but is it an exact twin or does it behave differently?
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-exit-commands-quit-exit-sys-exit-and-os-_exit
Python exit commands: quit(), exit(), sys.exit() and os._exit() - GeeksforGeeks
July 12, 2025 - The exit() in Python is defined as exit commands in python if in site.py and it works only if the site module is imported so it should be used in the interpreter only. It is like a synonym for quit() to make Python more user-friendly.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ atexit.html
atexit โ€” Exit handlers
The atexit module defines functions to register and unregister cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination. atexit runs these functio...
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ how-to-exit-python-a-quick-tutorial
How to Exit Python: A Quick Tutorial | DataCamp
April 5, 2024 - In production code, it is common practice to use the sys.exit() function from the sys module to exit Python without relying on the site module. The sys module is generally available but you will need to import it.
Find elsewhere
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-exit-how-to-use-an-exit-function-in-python-to-stop-a-program
Python Exit โ€“ How to Use an Exit Function in Python to Stop a Program
June 5, 2023 - By Shittu Olumide The exit() function in Python is used to exit or terminate the current running script or program. You can use it to stop the execution of the program at any point.
๐ŸŒ
Adam Johnson
adamj.eu โ€บ tech โ€บ 2021 โ€บ 10 โ€บ 10 โ€บ the-many-ways-to-exit-in-python
The Many Ways to Exit in Python - Adam Johnson
October 10, 2021 - We can use this to signal calling programs that an error occurred: ... If youโ€™re looking for a quick answer, you can stop reading here. Use raise SystemExit(<code>) as the obviousest way to exit from Python code and carry on with your life.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ exiting-a-python-program
Exiting a Python program - Python Morsels
February 21, 2022 - Whenever you're trying to exit your program while indicating that an error occurred, call sys.exit with a number besides 0. There's actually a shortcut for printing an error message and exiting at the same time. ... When sys.exit is called with a string, Python prints that string and exits with the code 1.
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-exit-command
Exit Function in Python
October 6, 2025 - This function is mainly intended for use in the interactive Python shell (REPL), but it also works in scripts for small-scale tasks. print("Starting the report generation...") # Suppose we check if a required file exists file_found = False if not file_found: print("Error: Required data file not found.") exit() # Stop the program here print("This line will not be executed.")
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ exit() in python
exit() in Python - Scaler Topics
May 4, 2023 - After writing the above code (python ... and it will print the argument. ... We can use the in-built exit() function to quit and come out of the execution loop of the program in Python....
๐ŸŒ
Analytics Vidhya
analyticsvidhya.com โ€บ home โ€บ python exit commands: quit(), exit(), sys.exit() and os._exit()
Python Exit Commands: quit(), exit(), sys.exit() and os._exit()
August 8, 2024 - It also terminates the execution of a Python program. Like quit(), exit() is best used in the Python interpreter.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ exit a python program, and python, completely.
r/learnpython on Reddit: Exit a Python program, and Python, COMPLETELY.
October 20, 2023 -

Trying to get the following program to exit:

import os

import tkinter as tk

root = tk.Tk()

root.protocol("WM_DELETE_WINDOW", root.destroy)

root.geometry("600x600")

# Create canvas

canvas = tk.Canvas(root, width=600, height=600)

canvas.pack()

# Create circle

circle = canvas.create_oval(10, 10, 60, 60, fill="red")

# Animation control variables

count = 0

# Animate function

def animate():

global count

# Move circle

canvas.coords(circle, 10, 10, 60, 60)

root.after(250, lambda: canvas.coords(circle, 540, 540, 590, 590))

root.after(500, lambda: canvas.coords(circle, 490, 10, 540, 60))

root.after(750, lambda: canvas.coords(circle, 10, 490, 60, 540))

count += 1

if count < 100:

root.after(1000, animate)

# Play function

# def play():

# global count

# count = 0

# animate()

# Create play button

# button = tk.Button(root, text="Play", command=play)

# button.pack()

# Start animation

animate()

root.mainloop()

# print("Great job!")

# Now trying to get the friggin window to close....

# root.quit()

# root.destroy()

# tk.mainloop.quit()

# sys.exit()

#if window_wont_close:

#os.system("taskkill /f /im python.exe")

Top answer
1 of 3
2
The root.mainloop() function creates an infinite loop, which means that any statements following it will not be executed unless the loop is interrupted. To exit the loop, consider adding a 'Quit' button to your application and set its command to root.destroy. Once you click this button, the loop will hopefully terminate.
2 of 3
1
The root.mainloop() call is a blocking function. The tkinter system loops in that function handling events and redrawing the screen, so putting any code after the call doesn't execute that code until the user clicks on the "close" widget or causes a shutdown from within the code itself. So you have to call root.destroy() within the code that is running. This seems to do what you want: import os import tkinter as tk root = tk.Tk() root.protocol("WM_DELETE_WINDOW", root.destroy) root.geometry("600x600") # Create canvas canvas = tk.Canvas(root, width=600, height=600) canvas.pack() # Create circle circle = canvas.create_oval(10, 10, 60, 60, fill="red") # Animation control variables count = 0 # Animate function def animate(): global count # Move circle canvas.coords(circle, 10, 10, 60, 60) root.after(250, lambda: canvas.coords(circle, 540, 540, 590, 590)) root.after(500, lambda: canvas.coords(circle, 490, 10, 540, 60)) root.after(750, lambda: canvas.coords(circle, 10, 490, 60, 540)) count += 1 if count < 10: # quicker testing root.after(1000, animate) else: root.destroy() animate() root.mainloop() print("Great job!") The above code is formatted as code. Note how it looks different from how you posted your code. The FAQ shows how to post code such that indentation is preserved.
๐ŸŒ
Interview Kickstart
interviewkickstart.com โ€บ home โ€บ blogs โ€บ learn โ€บ python exit commands
Python Exit Commands | Interview Kickstart
November 7, 2024 - Python exit commands explained: sys.exit(), quit(), Ctrl+D, and best practices for graceful program termination in scripts and REPL.
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ exit a python program in 3 easy ways!
Exit a Python Program in 3 Easy Ways! - AskPython
April 7, 2023 - As already mentioned, the exit() function can be considered an alternative to the quit() function, which enables us to terminate the execution of a Python program. ... After the first iteration completes and the exit() function executes immediately ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to exit python program if an if statement is true?
r/learnpython on Reddit: How to exit Python program if an if statement is true?
February 11, 2022 -

How to have Python exit a program provided the elif statement below is true? I tried exit(), break, and quit(), but what happened was the last thing the program said was Goodbye, and there was a blinking underscore, so the program was still running and the commands didn't work.

if numbers == 1:
    answer = input(f"How many?")
elif numbers == 0:
    answer = f"Exiting program..."
        print("Goodbye!")
    	exit()
else:
    answer = input(f"Let's go back.")
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-exit-a-python-script
How to Exit a Python script? - GeeksforGeeks
July 23, 2025 - There exist several ways of exiting ... to Use the exit() Function in Python. The "exit()" statement terminates the program immediately, preventing the execution of any subsequent code....
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ why is sys.exit() recommended over exit() or quit()
r/learnpython on Reddit: Why is sys.exit() recommended over exit() or quit()
July 21, 2020 -

In most questions asking how to stop code the recommended answer is sys.exit() or raising an exception. Why is exit() not suggested given it is simpler, not requiring import sys, and it does the same thing underneath?

e.g. https://www.reddit.com/r/learnpython/comments/hv7phs/how_do_i_stop_a_code/?utm_medium=android_app&utm_source=share)