Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Difference Between exit() and sys.exit() in Python

#1
Difference Between exit() and sys.exit() in Python

Problem: There are two similarly-named functions in Python, exit() and sys.exit(). What’s the difference between them, and when should I use one over the other?

Introduction


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 – exit() and sys.exit(). We will also learn the difference between exit() and sys.exit().

? 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


The exit() will straightforwardly end the execution of the Python code/script. The code that follows thereafter the exit() command won’t be executed.

Note:

  • 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=" ")

Output:

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 25, the 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. The 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.

#Trivia:

  • When we use the sys.exit() command, it raises the built-in SystemExit Exception. 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 raise SystemExit(s)
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!")

Output:

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.

Example:

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)

Output:

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()



exit() 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.
exit() belongs to the site.py module and works only if the site module is imported/present.
➥ 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 sys.exit() a better and convenient option.

Now, let us have a look at an example that will clarify things further.

➥ Example


In the following example, you will come across a couple of functions:

  • foo() – used to demonstrate the working principle of sys.exit()
  • func() – used to demonstrate the working principle of exit()
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()

Output:

Demonstrating sys.exit()
Abnormal Termination! Encountered SystemExit Demonstrating exit()
Use exit() or Ctrl-Z plus Return to exit

Explanation:

  • 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.

Conclusion


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.

? Read Here: How to Fix TypeError: Can’t Multiply Sequence by non-int of Type ‘float’ In Python?

I hope this article helped you to understand the difference between sys.exit() and exit() in Python. Please subscribe and stay tuned for more interesting tutorials. Happy learning! ?

Thank you Rashi Agarwal for helping me with the article!

The Complete Guide to PyCharm

  • 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!

The post Difference Between exit() and sys.exit() in Python first appeared on Finxter.



https://www.sickgaming.net/blog/2021/03/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python help() xSicKxBot 0 65 01-22-2021, 01:02 AM
Last Post: xSicKxBot
  [Tut] __getattr__ vs. __getattribute__ — What’s the Difference? xSicKxBot 0 45 01-20-2021, 11:30 AM
Last Post: xSicKxBot
  [Tut] Python complex() — A Useless Python Feature? xSicKxBot 0 73 12-19-2020, 02:05 AM
Last Post: xSicKxBot
  [Tut] Python next() xSicKxBot 0 69 11-22-2020, 08:17 AM
Last Post: xSicKxBot
  [Tut] Hello World! A Python One-Liner to Get Started with Python Quickly xSicKxBot 0 115 09-07-2020, 06:10 PM
Last Post: xSicKxBot
  [Tut] List Difference | The Most Pythonic Way xSicKxBot 0 155 06-27-2020, 02:51 PM
Last Post: xSicKxBot
  [Tut] Python Join List of Bytes (and What’s a Python Byte Anyway?) xSicKxBot 0 186 06-10-2020, 05:38 AM
Last Post: xSicKxBot
  [Tut] Python Re Dot xSicKxBot 0 317 01-28-2020, 08:01 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
AppleInsider - Logitech discontinues Har...
Last Post: xSicKxBot
Today 08:21 AM
» Replies: 0
» Views: 6
News - Legend Of Mana’s Physical Switch ...
Last Post: xSicKxBot
Today 08:20 AM
» Replies: 0
» Views: 6
News - Video: Hot Wheels Unleashed Dev R...
Last Post: xSicKxBot
Today 08:20 AM
» Replies: 0
» Views: 6
News - Robert DeNiro Was Originally Cast...
Last Post: xSicKxBot
Today 08:20 AM
» Replies: 0
» Views: 6
ISO: Staff Members for Website, Discord,...
Last Post: PeterCedly
Today 06:29 AM
» Replies: 3
» Views: 8175
(Indie Deal) Borderlands, Civ6, Mafia, N...
Last Post: xSicKxBot
Today 03:59 AM
» Replies: 0
» Views: 3
News - Video: 11 Exciting New Games Comi...
Last Post: xSicKxBot
Yesterday 10:09 PM
» Replies: 0
» Views: 6
News - Random: Someone Made The Among Us...
Last Post: xSicKxBot
Yesterday 10:09 PM
» Replies: 0
» Views: 5
News - Hotel Transylvania 4 Gets New Jul...
Last Post: xSicKxBot
Yesterday 10:09 PM
» Replies: 0
» Views: 5
News - This Week At Bungie – 4/08/2021
Last Post: xSicKxBot
Yesterday 05:23 PM
» Replies: 0
» Views: 5

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020