• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Terminate a Program or A Function in Python

Terminate a Program or A Function in Python

Author: Aditya Raj
Last Updated: April 28, 2023

While programming in Python, we sometimes need to stop the execution of the program based on specific conditions. In this article, we will discuss different ways to terminate a program in Python.

Table of Contents
  1. Stop the Execution  of a Function Using The Return Statement
  2. Stop the Execution  of a Function Using The sys Module
  3. Stop the Execution  of a Function Using The SystemExit Exception
  4. Terminate a Program Using the os Module in Python
  5. Terminate a Program Using The quit() Function in Python
  6. Terminate a Python Program Using The exit() Function
  7. What Function Should You Use to Terminate a Python Program?
  8. Conclusion

Stop the Execution  of a Function Using The Return Statement

To stop a function execution at any point, you can return a value from the function using the return statement. Once the return statement is executed, the execution of the function stops and the code after the return statement is not executed. You can observe this in the following example.

def myFunction():
    print("Inside the funcion. This satement will be printed")
    return -1
    print("Inside the function. This satement will not be printed.")
print("Outside the function. Calling the function.")
myFunction()
print("Outside the function after function returned.")

Output:

Outside the function. Calling the function.
Inside the funcion. This satement will be printed
Outside the function after function returned.

In the above code, the statement after the return statement in the function myFunction() will never be executed. The execution of the function stops as soon as the return statement is executed.

Stop the Execution  of a Function Using The sys Module

The sys module provides us with different functions to execute tasks. We can also stop the execution of a function in Python using the sys module. For this, we will use the exit() function defined in the sys module. 

The exit() function takes an integer as its input argument giving the exit status. The default value for the input argument is 0. After execution, the sys.exit() function raises the SystemExit exception. 

To stop the execution of a function using the sys.exit() function, we will execute the exit() function inside the function we want to stop. After this, the program will run into a SystemExit exception and the code execution will stop. You can observe this in the following example.

import sys
def myFunction():
    print("Inside the funcion. This satement will be printed")
    sys.exit(0)
    print("Inside the function. This satement will not be printed.")
print("Outside the function. Calling the function.")
myFunction()
print("Outside the function after function returned.")

Output:

Outside the function. Calling the function.
Inside the funcion. This satement will be printed

An exception has occurred, use %tb to see the full traceback.

SystemExit: 0

In the above example, you can observe that the program runs into the SystemExit exception once the sys.exit() function is executed.

To handle the exception smoothly, you can catch the SystemExit exception using Python try except blocks as shown below.

import sys
try:
    def myFunction():
        print("Inside the funcion. This satement will be printed")
        sys.exit(0)
        print("Inside the function. This satement will not be printed.")
    print("Outside the function. Calling the function.")
    myFunction()
    print("Outside the function after function returned.")
except SystemExit:
    print("Function terminated.")

Output:

Outside the function. Calling the function.
Inside the funcion. This satement will be printed
Function terminated.

In the above code, the statement after myFunction() in the try block will not be executed as the control of the program is transferred to the except block once the SystemExit exception occurs.

Stop the Execution  of a Function Using The SystemExit Exception

Instead of using the sys.exit() method, you can directly raise the SystemExit exception to terminate the execution of a program as shown below.

try:
    def myFunction():
        print("Inside the funcion. This satement will be printed")
        raise SystemExit
        print("Inside the function. This satement will not be printed.")
    print("Outside the function. Calling the function.")
    myFunction()
    print("Outside the function after function returned.")
except SystemExit:
    print("Function terminated.")

Output:

Outside the function. Calling the function.
Inside the funcion. This satement will be printed
Function terminated.

We can use sys.exit() method and the SystemExit exception to terminate a function’s execution. However, if we don’t handle the exception, the execution of the Python program will be stopped as you observed in the first example using the sys.exit() function.

Terminate a Program Using the os Module in Python

The os module provides us with the _exit() function to stop the execution of a Python program. Here, we need to understand that the os._exit() function kills the Python interpreter instead of just stopping the program. You can observe this in the following example.

import os
def myFunction():
        print("Inside the funcion. This satement might get printed")
        os._exit(0)
        print("Inside the function. This satement might get printed.")
print("Outside the function. Calling the function.")
myFunction()
print("Outside the function after function returned.")

Output:

In the above output, you can observe that the kernel has been killed after the execution of the os._exit() function.

The os._exit() function works by sending a signal to the operating system kernel. When executed, it sends a signal to the kernel to kill the Python interpreter. Once the kernel of the operating system accepts the signal and executes the command to kill the Python interpreter, all the Python programs will be terminated. However, there is a possibility that a few statements written after the os._exit() function in the Python program might also get executed at the time kernel receives the signal and terminates the Python interpreter.

Terminate a Program Using The quit() Function in Python

Instead of the os._exit() function, we can use the quit() function to terminate a Python program. The quit() function works in a similar way to the os._exit() function.

def myFunction():
        print("Inside the funcion. This satement might get printed")
        quit()
        print("Inside the function. This satement might get printed.")
print("Outside the function. Calling the function.")
myFunction()
print("Outside the function after function returned.")

The result of the above code is similar to the os._exit() example.

Terminate a Python Program Using The exit() Function

Instead of the quit() function, you can also use the exit() function to terminate a Python program. Both functions have the same working.

def myFunction():
        print("Inside the funcion. This satement might get printed")
        exit(0)
        print("Inside the function. This satement might get printed.")
print("Outside the function. Calling the function.")
myFunction()
print("Outside the function after function returned.")

What Function Should You Use to Terminate a Python Program?

The os._exit() function, exit() function, and quit() function terminate the Python interpreter. Hence, if you are running multiple programs parallelly, you should not use these functions. Otherwise, all the programs will be stopped as these functions terminate the interpreter itself.

You can use the sys.exit() method and the SystemExit exception along with the try-except blocks to terminate a program. To terminate a function, you can simply use a return statement.

Conclusion

In this article, we discussed different ways to stop a function and terminate a Python program. To learn more about programming, you can read this article on Python tuple index out-of-range exceptions. You might also like this article on how to convert string to variable name in Python. 

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us