3 ways to end a program in Python
Knowing how to end a program is important and can be helpful in many different situations. For example, if you're creating a simple game, you can exit when a specific user enters or when a certain condition is met. Let's explore the differences between 3 ways to stop Python programs through the following article!
1. Use quit() or exit()
One of the simplest ways to end a Python program is to use one of the available methods, quit() or exit(). When you call quit() or exit(), the program will terminate.
Note: The quit() and exit() functions do similar things, so which tool to choose is just a matter of personal preference.
Here's how you can use the quit() function to end a Python program:
for num in range(10): if num == 9: quit() print(num)
The sample program above will print integers from 0 to 8 on the console. When the number is 9, the program will exit. You can also use the quit() command to exit the Python Integrated Development and Learning Environment (IDLE), which allows you to run Python scripts interactively.
Note that both quit() and exit() rely on the site module, so you should not use them in a production environment. The next method, sys.exit(), is a better choice.
2. Use sys.exit()
When you call sys.exit() in your program, Python throws a SystemExit exception. It accepts an optional argument to specify an integer exit code (0 by default). You can also pass an object which will result in an exit code of 1 and will print the object's string value to standard error.
import sys # Remember to include this statement at the top of the module for num in range(10): if num == 5: sys.exit("You exited the program") print(num)
The output of the program will be as follows:
Note: Like the quit and exit methods, sys.exit() also throws a SystemExit exception. This means you can call sys.exit() or raise SystemExit(). Both accept an optional argument.
You should learn about the most important Python functions if you don't understand how the above code works.
3. Use os._exit()
The third way to exit a program is to use the special os._exit() method. You can pass it an optional argument to specify the exit status code. os._exit() comes from the os module and ends the process immediately without performing the usual cleanup operations that occur when a Python program exits.
Because this function exits without performing normal cleanup, you should only use it in special cases. According to the Python documentation, a typical example is a post-fork child process (a new process created with os.fork()).
The following is an example of using the os._exit() function to end a program:
import os import sys def child_process(): print("Child process is running.") os._exit(0) def main(): print("Parent process is running.") try: pid = os.fork() if pid == 0: # Code in the child process child_process() else: # Code in the parent process print(f"Parent process is continuing with child process PID: {pid}") except OSError as e: print(f"Fork failed: {e}") sys.exit(1) print("Parent process is done.") if __name__ == "__main__": main()
The above code will output as follows:
Which method should be used to terminate a program in Python?
Python provides many different methods to terminate a program. However, most of these methods do the same thing. This will ease the decision-making burden if you need to add an exit mechanism to your program when learning Python.
In short, sys.exit() should be the method you should use to end a program in Python. It throws a SystemExit exception with an optional exit code.
The quit() and exit() methods are more suitable when using the Python REPL. You should avoid them in production because they depend on the site module and are not always available. You rarely need to use os._exit(), unless you are working with process branching code.
You should read it
- How to install Python plugin to be able to execute Python programming on IntelliJ
- Package in Python
- How to Make a Self‐Writing Mosaic Program in Python
- Write a program to check duplicate values in Python
- Python online editor
- How to seamlessly integrate Python into Excel using PyXLL
- More than 100 Python exercises have solutions (sample code)
- Write an alarm clock program in Python
May be interested
- More than 100 Python exercises have solutions (sample code)more than 100 python code examples are shared by guy zhiwehu on github, however, the solution of this series is written on the old python version. following tipsmake.com will be vietnameseized and edited to suit python 3.x to help you learn and practice python.
- Write an alarm clock program in Pythonif you are new to python programming, writing an alarm program is a simple example for you to practice.
- The eval () function in Python.in this article, quantrimang will continue to introduce you to a built-in function in python, eval (). eval () is an interesting utility that allows you to run python code (this code is passed as parameters) right in the program.
- Programming Python on Android deviceusing python is one of the fastest ways to get started and test some simple code on android. further, when you are familiar with it, you can upgrade your phone with unique features only you have and can even build a full apk.
- How to Compile Python Scriptpython is a very popular language for programming. but what if the person running your program does not want or know how to run a python script? this article will teach you how to compile a python script into an executable. download...
- Bookmark 5 best Python programming learning websitesif you are a developer or you are studying and want to stick with this industry, learn python to add a highlight in your journey.
- How to Install Pythonpython is an interpreted, object-oriented, high-level programming language that is a great place for beginners to start learning how to program. python comes installed on macs and with linux, but you'll need to install it yourself if...
- How to Open a Python Filethis wikihow teaches you different ways to open and run a python script on windows, macos, and linux systems. simply installing the latest version of python 3 from python.org (or by using your linux distribution's package manager) gives...
- For in Python loopin this article, we will learn more about for for loop in python as well as its variations, how to use for to repeat a string of elements in python such as list, string or other iterative objects.
- Manage files and folders in Pythonpython also provides a variety of methods to handle various directory-related operations. in this article, we will learn about managing files and directories in python, namely creating folders, renaming folders, listing folders and working with them.