Program for How To End Program

Python Program for How To End Program

In Python, we can use one of the following methods to exit the program.

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

All of these functions have nearly identical functionality because they raise the SystemExit exception, which is the reason the Python interpreter exists, and no stack traceback is printed.

When we run a program in Python, we execute every line of code in the file, from top to bottom. Scripts normally terminate when the interpreter reaches the end of the file, but the execution can also be terminated programmatically.

Program for How To End Program in Python

1. sys.exit() Method:

In Python, use the sys. exit() function to exit the program. To exit the program, use the sys module’s built-in function sys. exit(). The sys. exit() function can be called at any time without fear of causing code corruption.

Syntax:

sys.exit([arg])

The sys. exit() function accepts an optional argument arg, which can be an integer representing the exit or another type of object.

Examples:

Example1:

import sys
gvn_numb = 10
if gvn_numb != 15:
    sys.exit("Number mismatch.Exiting from program")
else:
    print("The given numbers are matched")

Output:

Number mismatch.Exiting from program

Example2:

Input:

import sys
gvn_numb = 15
if gvn_numb != 15:
    sys.exit("Number mismatch.Exiting from program")
else:
    print("The given numbers are matched")

Output:

The given numbers are matched

2.quit() Method:

Use the quit() function to exit the Python program. quit() is a built-in Python function that raises the SystemExit exception and displays a message.

Syntax:

quit()

Examples:

Example1:

for itr in range(2, 6):
    print(itr*5)
    quit()

Output:

10

Example2:

Input:

for itr in range(1, 12):
    if(itr % 2 == 0):
        print(itr, end=" ")
        quit()

Output:

2

3.exit() Method:

In Python, use the exit() function to exit the program. The exit() function in Python is a built-in function that exits the program’s execution loop.

Syntax:

exit()

The exit() function is an alternative to the quit() function, which terminates the program’s execution.

That is for terminating a Python program.

Example1:

for itor in range(10):
    if itor == 5:
        exit()
    print(itor)

Output:

0
1
2
3
4

Example2:

for itor in range(20):
    if itor % 2 != 0 and itor > 8:
        exit()
    print(itor)

Output:

0
1
2
3
4
5
6
7
8