Problem: There are two similarly-named functions in Python,
sys.exit(). What’s the difference between them, and when should I use one over the other?
In contrast to programming languages like C, there is no
main() method in Python. Thus, when we run a program in Python, we essentially execute all the code in the top-level file, i.e., from top to bottom. The scripts typically exit themselves when Python tumbles off the end of the document, yet we can likewise call for program exit unequivocally with the help of exit commands. In this tutorial, we will learn about two different exit commands in Python –
sys.exit(). We will also learn the difference between
💡 When and why do we need the exit() commands in Python?
When you implement a program in Python, the code is executed consecutively until the end. However, there can be occasions when we require the program to end sooner than anticipated. This is where different exit commands come into the picture.
Although Python is a simple programming language, sometimes it might get a little complex. One such case is the utilization of different sorts of exit commands in Python.
⛔ exit() | Python
exit() will straightforwardly end the execution of the Python code/script. The code that follows thereafter the
exit() command won’t be executed.
- You can think of exit() as an alias for quit() (or vice-versa) in Python. They simply co-exist to make Python more user-friendly. However, it is not a good practice to use quit() and exit() in production code and should only be reserved for use in the interpreter.
exit()command generates the following message when printed:
- Use exit() or Ctrl-D (i.e. EOF) to exit
- ➥ Example:
for no in range(15, 30): if no > 25: print("\n", exit) # printing the exit message # When the value of no becomes 10 then the program is forced to exit exit() print(no, end=" ")
15 16 17 18 19 20 21 22 23 24 25 Use exit() or Ctrl-Z plus Return to exit
Explanation: As soon as
no is greater than
exit() method is executed, and the program terminates after printing the exit message.
⛔ sys.exit() | Python
You can call the
sys.exit() to exit from the Python code with exit status as
arg (argument) can be anything like an integer or another object-the
arg defaults to zero, which indicates successful termination. You can set
arg to a non-zero value to denote an abnormal termination of the code.
- When we use the
sys.exit()command, it raises the built-in
SystemExitException. Along these lines, you can catch it as usual to block early exits and perform cleanup activities when necessary.
sys.exit(s)can be considered just as a shorthand for
import sys try: sys.exit() print("This Line won't be Executed!") except SystemExit: print("SystemExit Exception terminated the program!") finally: print("Perform Cleanup Activities!")
SystemExit Exception terminated the program! Perform Cleanup Activities!
Now, let us have a look at an example to get hold of the
sys.exit() method in Python.
import sys num = int(input("Enter a number: ")) if num < 20: # exits the program sys.exit("Exiting! The number is less than 20.") else: print("Number = ", num)
Enter a number: 5 Exiting! The number is less than 20.
Explanation: As soon as the user input is less than 20, the sys.exit() command gets executed, which prints the
arg as exit status, i.e., “Exiting! The number is less than 20.“
✨ Difference Between exit() and sys.exit()
|➥ Should not be used while dealing with production code. |
➥ It can be used within an interpreter.
|➥ sys.exit() is a good option if you are dealing with production code.|
➥ The site module is automatically imported during start-up, except if the -S command-line option is used.
|➥ sys module is always available, which makes |
Now, let us have a look at an example that will clarify things further.
In the following example, you will come across a couple of functions:
- foo() – used to demonstrate the working principle of
- func() – used to demonstrate the working principle of
import sys def foo(): try: print("Demonstrating sys.exit()") sys.exit() print("This line will not be executed!") except SystemExit: # argument denoting exit status print("Abnormal Termination! Encountered SystemExit") def func(): print("Demonstrating exit()") print(exit) exit() # lines after this statement are ignored and are not executed print("The previous command executes ignoring all the lines after the command") # Calling both the function: foo() print() func()
Demonstrating sys.exit() Abnormal Termination! Encountered SystemExit Demonstrating exit() Use exit() or Ctrl-Z plus Return to exit
- Inside foo(), line 8 is ignored because Python encountered the sys.exit(). As a result the control moved on to the except block and the custom error message was displayed.
- Inside func(), line 18 was not executed since Python encountered the exit() method and the program was terminated.
🤔 A Commonly Asked Question: Difference between exit(0) and exit(1) in Python?
exit(0) denotes a successful exit of the program/script without the occurrence of any errors/problems, i.e.; it signifies successful execution. In contrast, a non-zero exit like
exit(1) denotes an abnormal termination of the code. At times, error codes can also signify the type of problem encountered, which leads to the abrupt termination of the script.
To summarize this discussion, you should remember that sys.exit() is more elegant, and a SystemExit Exception will be thrown after the call. The exit() command abruptly terminates the Python script, and the rest of the statements are not executed.
Thank you Rashi Agarwal for helping me with the article!
- Do you want to master the most popular Python IDE fast?
- This course will take you from beginner to expert in PyCharm in ~90 minutes.
- For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.
Join the PyCharm Masterclass now, and master PyCharm by tomorrow!