How to Check If a Function Returns None in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a function returns None in Python. The lab guides you through understanding function return values by creating a simple Python script with a function that returns the sum of two numbers. You will then execute the script and observe the output.

The lab continues by modifying the function to return different data types, and ultimately focuses on scenarios where a function might not explicitly return a value, resulting in a None return. You will learn how to capture the return value of a function and then check if that value is None using the is operator.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/arguments_return("Arguments and Return Values") subgraph Lab Skills python/conditional_statements -.-> lab-559522{{"How to Check If a Function Returns None in Python"}} python/function_definition -.-> lab-559522{{"How to Check If a Function Returns None in Python"}} python/arguments_return -.-> lab-559522{{"How to Check If a Function Returns None in Python"}} end

Learn About Function Return Values

In this step, you'll learn about function return values in Python. Functions are reusable blocks of code that perform specific tasks. Often, you'll want a function to give you back a result after it finishes its work. This result is called the return value.

Let's start by creating a simple Python script that defines a function with a return value.

  1. Open the VS Code editor in the LabEx environment.

  2. Create a new file named calculate.py in the ~/project directory.

    ~/project/calculate.py
  3. Add the following code to calculate.py:

    def add(x, y):
        """This function adds two numbers and returns the result."""
        sum = x + y
        return sum
    
    ## Call the function and print the returned value
    result = add(5, 3)
    print(result)

    In this code:

    • We define a function called add that takes two arguments, x and y.
    • Inside the function, we calculate the sum of x and y and store it in a variable called sum.
    • The return sum statement specifies that the function should return the value of sum when it's called.
    • Outside the function, we call the add function with the arguments 5 and 3, and store the returned value in a variable called result.
    • Finally, we use the print() function to display the value of result.
  4. Save the calculate.py file.

  5. Open a terminal in the WebIDE.

  6. Run the script using the following command:

    python calculate.py

    You should see the following output:

    8

    This output shows that the add function correctly calculated the sum of 5 and 3, and returned the value 8, which was then printed to the console.

Now, let's modify the function to return a different type of value, such as a string.

  1. Open the calculate.py file in VS Code.

  2. Modify the code to the following:

    def greet(name):
        """This function returns a greeting message."""
        message = "Hello, " + name + "!"
        return message
    
    ## Call the function and print the returned value
    greeting = greet("LabEx User")
    print(greeting)

    In this code:

    • We define a function called greet that takes one argument, name.
    • Inside the function, we create a greeting message by concatenating the string "Hello, ", the value of the name argument, and the string "!".
    • The return message statement specifies that the function should return the greeting message.
    • Outside the function, we call the greet function with the argument "LabEx User", and store the returned value in a variable called greeting.
    • Finally, we use the print() function to display the value of greeting.
  3. Save the calculate.py file.

  4. Run the script again using the following command:

    python calculate.py

    You should see the following output:

    Hello, LabEx User!

    This output shows that the greet function correctly created a greeting message and returned it, which was then printed to the console.

Capture the Return Value

In the previous step, you learned how to define functions that return values. Now, you'll learn how to capture and use those return values in your programs. Capturing the return value means storing the value returned by a function in a variable so you can use it later.

Let's continue with the calculate.py file you created in the previous step. We'll modify the script to perform more operations and capture the return values.

  1. Open the calculate.py file in VS Code.

  2. Modify the code to the following:

    def add(x, y):
        """This function adds two numbers and returns the result."""
        sum = x + y
        return sum
    
    def subtract(x, y):
        """This function subtracts two numbers and returns the result."""
        difference = x - y
        return difference
    
    ## Call the functions and capture the return values
    num1 = 10
    num2 = 5
    
    sum_result = add(num1, num2)
    print("The sum of", num1, "and", num2, "is:", sum_result)
    
    difference_result = subtract(num1, num2)
    print("The difference between", num1, "and", num2, "is:", difference_result)

    In this code:

    • We define two functions: add and subtract.
    • We call the add function with the arguments num1 and num2, and store the returned value in a variable called sum_result.
    • We call the subtract function with the arguments num1 and num2, and store the returned value in a variable called difference_result.
    • We use the print() function to display the values of sum_result and difference_result, along with descriptive text.
  3. Save the calculate.py file.

  4. Run the script using the following command:

    python calculate.py

    You should see the following output:

    The sum of 10 and 5 is: 15
    The difference between 10 and 5 is: 5

    This output shows that we successfully captured the return values of the add and subtract functions and used them in our program.

Now, let's create a more complex example where we use the return value of one function as an argument to another function.

  1. Open the calculate.py file in VS Code.

  2. Modify the code to the following:

    def add(x, y):
        """This function adds two numbers and returns the result."""
        sum = x + y
        return sum
    
    def multiply(x, y):
        """This function multiplies two numbers and returns the result."""
        product = x * y
        return product
    
    ## Call the functions and capture the return values
    num1 = 5
    num2 = 3
    
    sum_result = add(num1, num2)
    product_result = multiply(sum_result, 2)  ## Use the return value of add as an argument to multiply
    
    print("The sum of", num1, "and", num2, "is:", sum_result)
    print("The product of the sum and 2 is:", product_result)

    In this code:

    • We define two functions: add and multiply.
    • We call the add function with the arguments num1 and num2, and store the returned value in a variable called sum_result.
    • We call the multiply function with the arguments sum_result and 2. This demonstrates how the return value of add can be used as an input to multiply. We store the returned value in a variable called product_result.
    • We use the print() function to display the values of sum_result and product_result, along with descriptive text.
  3. Save the calculate.py file.

  4. Run the script using the following command:

    python calculate.py

    You should see the following output:

    The sum of 5 and 3 is: 8
    The product of the sum and 2 is: 16

    This output shows that we successfully used the return value of one function as an argument to another function, demonstrating the power and flexibility of function return values.

Check If the Return Value Is None

In some cases, a function might not always return a meaningful value. In such situations, it can return None. None is a special value in Python that represents the absence of a value. It's important to check if a function returns None before using its return value to avoid errors.

Let's modify the calculate.py file to include a function that might return None.

  1. Open the calculate.py file in VS Code.

  2. Modify the code to the following:

    def divide(x, y):
        """This function divides x by y and returns the result.
        If y is 0, it returns None to avoid division by zero errors.
        """
        if y == 0:
            return None
        else:
            return x / y
    
    ## Call the function and check if the return value is None
    numerator = 10
    denominator = 0
    
    result = divide(numerator, denominator)
    
    if result is None:
        print("Cannot divide by zero!")
    else:
        print("The result of", numerator, "/", denominator, "is:", result)
    
    denominator = 2
    result = divide(numerator, denominator)
    
    if result is None:
        print("Cannot divide by zero!")
    else:
        print("The result of", numerator, "/", denominator, "is:", result)

    In this code:

    • We define a function called divide that takes two arguments, x and y.
    • Inside the function, we check if y is equal to 0. If it is, we return None to avoid a division by zero error.
    • If y is not 0, we calculate the result of x / y and return it.
    • Outside the function, we call the divide function with a denominator of 0.
    • We check if the returned value is None using the is operator.
    • If the returned value is None, we print an error message.
    • Otherwise, we print the result of the division.
    • We then call the divide function again with a valid denominator and print the result.
  3. Save the calculate.py file.

  4. Run the script using the following command:

    python calculate.py

    You should see the following output:

    Cannot divide by zero!
    The result of 10 / 2 is: 5.0

    This output shows that the program correctly handled the case where the denominator was 0 and printed an appropriate error message. It also shows that the program correctly calculated and printed the result when the denominator was not 0.

It's important to use the is operator to check if a value is None because None is a singleton object in Python. This means that there is only one instance of None in the entire program. Using the == operator might not always work correctly because it compares the values of the objects, not the objects themselves.

Summary

In this lab, you learned about function return values in Python. You created a function called add that takes two arguments, calculates their sum, and returns the result. You then called the function, stored the returned value in a variable, and printed it to the console.

The lab demonstrated how functions can return values of different types, such as integers. This allows functions to perform calculations or operations and provide the results back to the calling code for further use.