Normally a python program will exit automatically when the program ends. But some situations may arise when we would want to exit the program on meeting a condition or maybe we want to exit our program after a certain period of time. Therefore to accomplish such task we have to send an exit command to the python program.
There are 4 different commands to exit a python program. Let's learn all the four. Let's get straight to the list.
The most accurate way to exit a python program is using
Using this command will exit your python program and will also raise SystemExit exception which means you can handle this exception in try/except blocks. Such as this.
try: sys.exit() except SystemExit : print("I will not exit this time')
A user-friendly way to quit a python program. Just like
quit()raises SystemExit exception, the only difference is that it relies on site module which is imported automatically during startup, therefore it may be bad for use in production.
Just another way of writing
exit()or you can say an alias for
All of the above commands does essentially the same thing, that is, raising a SystemExit exception. However,
os.exit()works a bit differently, as it exits the program without calling cleanup handlers, flushing stdio buffers, etc. Therefore it's not a standard way to exit a python program.
There's another way to exit a python program but it's actually not a command but more of a hotkey for your python program. And it is
This will raise a KeyboardInterrupt exception and will exit the python program. We normally use this command when we want to break out of the loop.
Great, we have learned all the different ways to exit a python program. Now let me show you a small example showing how to exit a python script in an if statement
names =  print("Enter the name of the student in your class one by one") while True: name = input("Name of student: ") if not name: print("Students in your class are:\n"+"\n".join(names)) sys.exit() else: names.append(name)
In the above example, it will continuously ask for the name of the student and append it to the names list until the user will input a blank name or we can say until the user leave the field empty and press the enter key.
Enter the name of the student in your class one by one Name of student: Mark Name of student: Jeff Name of student: Zuck Name of student: Anthony Name of student:
Students in your class are: Mark Jeff Zuck Anthony
That's it! I hope you find this article useful. If you have any doubts or think something is wrong then leave a comment below.