Python

How to Exit from the Python Program

Sometimes it requires to exit from the Python program based on a particular condition. Many built-in functions and commands exist in Python to terminate from the Python program. The exit(), quit(), sys.exit(), and os._exit() are the built-in functions of Python that can be used to exit from the program. The KeyboardInterrupt and raise SystemExit statement can be used also to terminate the program. The uses of these built-in functions and the statement have been shown in this tutorial.

Example 1: Use of Exit() Function

The exit() function is the most common function of the Python to terminate from the script. Create a Python file with the following script to know the use of the exit() function. In the script, the value of the n has been initialized to 1 and the loop will be continued until it becomes more than 10. The ‘if’ statement has been used inside the loop to terminate the script when the value of n will be 6.

#Initialize the counter variable, n
n=1
#Iterate the loop until the value of n <=10
while n<=10:
    print("The value of n = ",n)
    #Increment the value of n
    n = n + 1
    #Check the value of n and terminate from the loop using exit() when n=6
    if n==6 :
        print("Terminate from the script.")
        exit()

Output
The following output will be appeared after executing the above script.

Example 2: Use of Quit() Function

The quit() function is another most common function of the Python to terminate from the script. Create a Python file with the following script to know the use of the quit() function. In the script, an associative array has been defined and the ‘for’ loop has been used to iterate the values of the array. The quit() function has been used inside the loop to terminate the script when the iteration value is ‘USA’.

The quit() function can be used in a Python program in the following way:

#Declare a list of 6 elements
countries = ["Bangladesh", "Germany", "Japan", "Norway","USA", "Australia"]
#Iterate the values of the list using 'for' loop
for country in countries:
     print(country)
     #Check the value of the list is 'USA' or not
     if country == "USA":
          print("Terminate from the script.")
          #Terminate from the loop
          quit()

Output
The following output will be appeared after executing the above script.

Example 3: Use of sys.exit() Function

The exit() function does not require to import any module but it depends on the site module and shows a message to kill the program or not. The sys.exit() function that is under the sys module is better than the exit() function because it does not ask before closing the program. Create a Python file with the following script to know the use of sys.exit() function for terminating the script. Here, the sys.exit() function will be executed if the filename taken from the user does not exist in the current location and the script will be terminated by showing an error message.

#Import sys module
import sys
#Import path from os module
import os.path

#Take the filename from the user
filename = input("Enter the filename: ")
#Check the file exist or not
if os.path.exists(filename):
    fh = open(filename, 'r')
    lines = fh.readlines()

    #Print the content of the file
    for line in lines:
        print(line)
else:
    #Terminate from the script with the error message
    sys.exit("File does not exist.")

Output
The following output will be appeared after executing the above script.

Example 4: Use of os._exit() Function

The os._exit() function which is under the os module is another function to terminate from the Python script. Create a Python file with the following script to know the use of os._exit() function to exit from the Python program. In the script, a number input will be taken from the user. If the taken value is not a number, then the isdigit() function will return false and the script will be terminated. Otherwise, the input value will be printed.

#Import os module
import os

#Take a number from the user
number = input("Enter a number: ")
#Check the input value is a digit or not
if number.isdigit() == False:
    #Print the error message
    print("The number is not a digit.")
    #Terminate from the script
    os._exit(0)
else:
    #Print the value taken from the user
    print("The input value is", number)

Output
The following output will be appeared after executing the above script.

Example 5: Use of KeyboardInterrupt and Raise SystemExit Statement

When the user presses Ctrl+C or Ctrl+Z to interrupt the running program then the KeyBoardInterrupt exception will be generated. The SystemExit statement is raised to catch the exception for terminating the program. Create a Python file with the following script to know the use of the KeyBoardInterrupt exception and SystemExit statement. In the script, the number input will be taken from the user and wait for 5 seconds inside the try block. If the user presses Ctrl+C or Ctrl+Z within 5 seconds after running the script, then the SystemExit statement will be raised and terminated from the program.

#Import time module
import time
#Define try block
try:
    #Take the name from the user
    name = input("What is your name?\n ")
    #Check the input value contains alphabets or not
    if name.isalpha() == True:
       print("Welcome,", name)
    time.sleep(5)
    print("Done...")
#Define except block
except KeyboardInterrupt:
    #Print error message
    print("\nTerminated from the program.")
    #Terminate from the script
    raise SystemExit

Output
The following output will be appeared after executing the above script.

Conclusion

Different ways to terminate the program have been shown in this tutorial by using multiple examples. The uses of many built-in functions and the statement for terminating from the script have been explained here to help the Python users to add Python script for the program termination when required.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.