How to Check If a Function Returns a Specific Value in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a Python function returns a specific value. The lab focuses on understanding function returns using the return statement and verifying the output.

You'll start by creating a Python script with a function that calculates the sum of two numbers and returns the result. You'll then execute the script and observe the output. Finally, you'll modify the script to return different values based on a condition and verify the returned value.


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-559521{{"How to Check If a Function Returns a Specific Value in Python"}} python/function_definition -.-> lab-559521{{"How to Check If a Function Returns a Specific Value in Python"}} python/arguments_return -.-> lab-559521{{"How to Check If a Function Returns a Specific Value in Python"}} end

Understand Function Returns

In this step, you will learn about function returns 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 is done using the return statement.

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_sum.py in the ~/project directory.

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

    def calculate_sum(x, y):
        """
        This function calculates the sum of two numbers.
        """
        sum_result = x + y
        return sum_result
    
    ## Example usage:
    num1 = 10
    num2 = 5
    result = calculate_sum(num1, num2)
    print("The sum of", num1, "and", num2, "is", result)

    In this code:

    • We define a function called calculate_sum 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_result.
    • The return sum_result statement sends the value of sum_result back to the caller of the function.
    • We then call the function with num1 = 10 and num2 = 5, and store the returned value in the result variable.
    • Finally, we use the print() function to display the result.
  4. Now, run the script using the following command in the terminal:

    python ~/project/calculate_sum.py

    You should see the following output:

    The sum of 10 and 5 is 15

    This output confirms that the function correctly calculated the sum and returned the value, which was then printed to the console.

  5. Let's modify the script to return a different value based on a condition. Edit the calculate_sum.py file to include the following:

    def calculate_sum(x, y):
        """
        This function calculates the sum of two numbers.
        If the sum is greater than 10, it returns double the sum.
        """
        sum_result = x + y
        if sum_result > 10:
            return sum_result * 2
        else:
            return sum_result
    
    ## Example usage:
    num1 = 10
    num2 = 5
    result = calculate_sum(num1, num2)
    print("The sum of", num1, "and", num2, "is", result)
    
    num3 = 2
    num4 = 3
    result2 = calculate_sum(num3, num4)
    print("The sum of", num3, "and", num4, "is", result2)

    Here, we've added a conditional statement (if sum_result > 10:) to check if the sum is greater than 10. If it is, the function returns double the sum; otherwise, it returns the original sum.

  6. Run the script again:

    python ~/project/calculate_sum.py

    You should now see the following output:

    The sum of 10 and 5 is 30
    The sum of 2 and 3 is 5

    The first call to calculate_sum returns 30 because the sum (15) is greater than 10, so it's doubled. The second call returns 5 because the sum (5) is not greater than 10.

Call Function and Capture Output

In this step, you will learn how to call a function and capture its output in Python. Capturing the output of a function allows you to use the returned value in further calculations or operations within your script.

We'll continue using the calculate_sum.py file from the previous step. If you haven't completed the previous step, please create the file with the following content:

def calculate_sum(x, y):
    """
    This function calculates the sum of two numbers.
    If the sum is greater than 10, it returns double the sum.
    """
    sum_result = x + y
    if sum_result > 10:
        return sum_result * 2
    else:
        return sum_result

## Example usage:
num1 = 10
num2 = 5
result = calculate_sum(num1, num2)
print("The sum of", num1, "and", num2, "is", result)

num3 = 2
num4 = 3
result2 = calculate_sum(num3, num4)
print("The sum of", num3, "and", num4, "is", result2)

Now, let's modify the script to capture the output of the calculate_sum function and perform additional operations with it.

  1. Open the calculate_sum.py file in the VS Code editor.

  2. Modify the script as follows:

    def calculate_sum(x, y):
        """
        This function calculates the sum of two numbers.
        If the sum is greater than 10, it returns double the sum.
        """
        sum_result = x + y
        if sum_result > 10:
            return sum_result * 2
        else:
            return sum_result
    
    ## Example usage:
    num1 = 10
    num2 = 5
    result = calculate_sum(num1, num2)
    print("The sum of", num1, "and", num2, "is", result)
    
    ## Capture the output and perform an additional operation
    final_result = result + 20
    print("The final result after adding 20 is:", final_result)
    
    num3 = 2
    num4 = 3
    result2 = calculate_sum(num3, num4)
    print("The sum of", num3, "and", num4, "is", result2)
    
    ## Capture the output and perform an additional operation
    final_result2 = result2 * 2
    print("The final result after multiplying by 2 is:", final_result2)

    In this modified script:

    • We call the calculate_sum function with num1 and num2, and store the returned value in the result variable.
    • We then add 20 to the result and store it in final_result.
    • Finally, we print the value of final_result.
    • We also call the calculate_sum function with num3 and num4, and store the returned value in the result2 variable.
    • We then multiply result2 by 2 and store it in final_result2.
    • Finally, we print the value of final_result2.
  3. Run the script using the following command:

    python ~/project/calculate_sum.py

    You should see the following output:

    The sum of 10 and 5 is 30
    The final result after adding 20 is: 50
    The sum of 2 and 3 is 5
    The final result after multiplying by 2 is: 10

    This output demonstrates that you can successfully call a function, capture its returned value, and use that value in subsequent operations within your script.

Compare Output with Expected Value

In this step, you will learn how to compare the output of a function with an expected value. This is a crucial part of testing and ensuring that your functions are working correctly. By comparing the actual output with the expected output, you can identify and fix any errors in your code.

We'll continue using the calculate_sum.py file from the previous steps. If you haven't completed the previous steps, please create the file with the following content:

def calculate_sum(x, y):
    """
    This function calculates the sum of two numbers.
    If the sum is greater than 10, it returns double the sum.
    """
    sum_result = x + y
    if sum_result > 10:
        return sum_result * 2
    else:
        return sum_result

## Example usage:
num1 = 10
num2 = 5
result = calculate_sum(num1, num2)
print("The sum of", num1, "and", num2, "is", result)

## Capture the output and perform an additional operation
final_result = result + 20
print("The final result after adding 20 is:", final_result)

num3 = 2
num4 = 3
result2 = calculate_sum(num3, num4)
print("The sum of", num3, "and", num4, "is", result2)

## Capture the output and perform an additional operation
final_result2 = result2 * 2
print("The final result after multiplying by 2 is:", final_result2)

Now, let's add a function to compare the output with an expected value and print a message indicating whether the test passed or failed.

  1. Open the calculate_sum.py file in the VS Code editor.

  2. Modify the script as follows:

    def calculate_sum(x, y):
        """
        This function calculates the sum of two numbers.
        If the sum is greater than 10, it returns double the sum.
        """
        sum_result = x + y
        if sum_result > 10:
            return sum_result * 2
        else:
            return sum_result
    
    def compare_output(actual_output, expected_output):
        """
        This function compares the actual output with the expected output.
        """
        if actual_output == expected_output:
            print("Test passed!")
        else:
            print("Test failed. Expected:", expected_output, "Actual:", actual_output)
    
    ## Example usage:
    num1 = 10
    num2 = 5
    result = calculate_sum(num1, num2)
    print("The sum of", num1, "and", num2, "is", result)
    
    ## Capture the output and perform an additional operation
    final_result = result + 20
    print("The final result after adding 20 is:", final_result)
    
    ## Compare the output with the expected value
    expected_final_result = 50
    compare_output(final_result, expected_final_result)
    
    num3 = 2
    num4 = 3
    result2 = calculate_sum(num3, num4)
    print("The sum of", num3, "and", num4, "is", result2)
    
    ## Capture the output and perform an additional operation
    final_result2 = result2 * 2
    print("The final result after multiplying by 2 is:", final_result2)
    
    ## Compare the output with the expected value
    expected_final_result2 = 10
    compare_output(final_result2, expected_final_result2)

    In this modified script:

    • We define a function called compare_output that takes two arguments: actual_output and expected_output.
    • Inside the function, we compare the actual_output with the expected_output.
    • If they are equal, we print "Test passed!".
    • If they are not equal, we print "Test failed." along with the expected and actual values.
    • We then call the compare_output function with final_result and expected_final_result to compare the output of the first calculation with the expected value of 50.
    • We also call the compare_output function with final_result2 and expected_final_result2 to compare the output of the second calculation with the expected value of 10.
  3. Run the script using the following command:

    python ~/project/calculate_sum.py

    You should see the following output:

    The sum of 10 and 5 is 30
    The final result after adding 20 is: 50
    Test passed!
    The sum of 2 and 3 is 5
    The final result after multiplying by 2 is: 10
    Test passed!

    This output demonstrates that you can successfully compare the output of a function with an expected value and determine whether the test passed or failed.

Summary

In this lab, the first step focuses on understanding function returns in Python. It involves creating a calculate_sum.py script that defines a function, calculate_sum(x, y), which calculates the sum of two input numbers and returns the result using the return statement. The script then calls this function with sample values and prints the returned sum to the console, demonstrating how a function can return a value that can be captured and used elsewhere in the code.

The initial script is then modified to return different values based on a condition, further illustrating the flexibility of function returns. This step reinforces the concept of functions as reusable blocks of code that can provide specific outputs based on their inputs and internal logic.