How to End Program in Python
To exit the program in Python, we can use one of the following methods.
All these functions have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exists, and no stack traceback is printed.
When we run a program in Python, we execute all the code in the file line by line, from top to bottom. Scripts normally terminate when the interpreter reaches the end of the file, but we can also terminate the execution programmatically.
Python end program
To end the program in Python, use the sys.exit() function. Python sys module contains a built-in function called sys.exit() to exit the program. The sys.exit() function can be used at any point in time without worrying about corruption in the code.
The sys.exit() function takes an optional argument arg can be an integer giving the exit or another type of object.
Let’s end the python program using the sys.exit() function.
import sys data = 21 if data != 19: sys.exit("Numbers do not match") else: print("Validation of values completed!!")
Numbers do not match
In this example, we are exiting the program because the numbers don’t match. We passed a string while exiting the program.
Terminate Python program using quit()
To terminate the Python program, use the quit() function. The quit() is a built-in Python function that is used to raise the SystemExit exception, and it gives you a message.
for x in range(1, 5): print(x*19) quit()
After printing the first value of the iteration, we use the quit() function to stop the program execution.
Exit the program using the exit() function in Python
To exit the program in Python, use the exit() function. The exit() is a built-in function that quits and comes out of the execution loop of the program in Python.
See the following code.
for i in range(5): if i == 3: print(exit) exit() print(i)
0 1 2 Use exit() or Ctrl-D (i.e. EOF) to exit
The exit() function can be considered as an alternative to the quit() function, which terminates the execution of the program.
That is it for ending a program in Python.