AppDividend
Latest Code Tutorials

How to End Program in Python

0

To exit the program in Python, we can use one of the following methods.

  1. sys.exit()
  2. quit()
  3. exit()

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.

Syntax

sys.exit([arg])

Parameters

The sys.exit() function takes an optional argument arg can be an integer giving the exit or another type of object.

Example

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!!")

Output

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.

Syntax

quit()

Example

We are using for statement with range() function to iterate the series of numbers, but on the first iteration, we are terminating the program using the quit() function.

for x in range(1, 5):
    print(x*19)
    quit()

Output

19

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.

Syntax

exit()

Example

See the following code.

for i in range(5):

    if i == 3:
        print(exit)
        exit()
    print(i)

Output

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.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.