How To Check If A Function Returns None Python

In this tutorial, we will learn how to check if a Python function returns None. By understanding how to identify a function that yields None, we can better handle certain scenarios within our code, avoid potential errors, and improve code readability. Without further ado, let’s dive into the process of checking if a function returns None in Python.

Step 1: Define the Function

First, let’s define a simple function that either returns a value or returns None. For the purposes of this tutorial, we will create a function called example_function that takes an integer as an input and returns its square if the input is even; otherwise, it returns None.

Step 2: Call the Function

Now we can call example_function with various input values and store its return value in a variable called result.

Step 3: Check If the Function Returns None

To check if result contains None, you can use an if statement and the is keyword. The is keyword checks for object identity, which means it verifies if two variables point to the same object. Since None is a singleton object in Python, we can safely use the is keyword to check if the function returned None.

Full Code

Let’s take a look at the full code:

Output

Function returned a value: 16
Function returned None

Conclusion

In this tutorial, we learned how to check if a Python function returns None. By understanding how to identify such functions, you can better handle specific scenarios within your code, avoid potential errors, and improve code readability. This knowledge is fundamental for writing clean, efficient Python code and for debugging your applications effectively.