Python Exit Command using exit() Function
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. It too gives a message when printed and terminate a program in Python.
Example: In the provided code, when i
is equal to 5, it prints “exit” and attempts to exit the Python interpreter using the exit()
function. If i
is not equal to 5, it prints the value of i
.
Python3
for i in range ( 10 ): if i = = 5 : print (exit) exit() print (i) |
Output:
0
1
2
3
4
Use exit() or Ctrl-D (i.e. EOF) to exit
Python exit commands: quit(), exit(), sys.exit() and os._exit()
The functions quit(), exit(), sys.exit(), and os._exit() have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exits and no stack traceback is printed. We can catch the exception to intercept early exits and perform cleanup activities; if uncaught, the interpreter exits as usual. In this article, we will see how to exit from the Python program.