如何检查 Python 函数是否返回特定值

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在这个实验中,你将学习如何检查 Python 函数是否返回特定值。本实验重点在于理解如何使用 return 语句返回函数结果,并验证输出。

你将首先创建一个 Python 脚本,其中包含一个计算两个数字之和并返回结果的函数。然后,你将执行该脚本并观察输出。最后,你将修改脚本,使其根据条件返回不同的值,并验证返回值。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) 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{{"如何检查 Python 函数是否返回特定值"}} python/function_definition -.-> lab-559521{{"如何检查 Python 函数是否返回特定值"}} python/arguments_return -.-> lab-559521{{"如何检查 Python 函数是否返回特定值"}} end

理解函数返回值

在这一步中,你将学习 Python 中的函数返回值。函数是执行特定任务的可重用代码块。通常,你会希望函数在完成工作后返回一个结果。这可以通过 return 语句来实现。

让我们从创建一个定义了返回值的简单 Python 脚本开始。

  1. 在 LabEx 环境中打开 VS Code 编辑器。

  2. ~/project 目录下创建一个名为 calculate_sum.py 的新文件。

    ~/project/calculate_sum.py
  3. calculate_sum.py 文件中添加以下代码:

    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)

    在这段代码中:

    • 我们定义了一个名为 calculate_sum 的函数,它接受两个参数 xy
    • 在函数内部,我们计算 xy 的和,并将其存储在一个名为 sum_result 的变量中。
    • return sum_result 语句将 sum_result 的值返回给函数的调用者。
    • 然后,我们使用 num1 = 10num2 = 5 调用该函数,并将返回值存储在 result 变量中。
    • 最后,我们使用 print() 函数显示结果。
  4. 现在,在终端中使用以下命令运行脚本:

    python ~/project/calculate_sum.py

    你应该会看到以下输出:

    The sum of 10 and 5 is 15

    这个输出确认了函数正确计算了和并返回了值,然后该值被打印到了控制台。

  5. 让我们修改脚本,使其根据条件返回不同的值。编辑 calculate_sum.py 文件,添加以下内容:

    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)

    在这里,我们添加了一个条件语句 (if sum_result > 10:) 来检查和是否大于 10。如果是,则函数返回和的两倍;否则,返回原始的和。

  6. 再次运行脚本:

    python ~/project/calculate_sum.py

    你现在应该会看到以下输出:

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

    第一次调用 calculate_sum 返回 30,因为和(15)大于 10,所以被加倍。第二次调用返回 5,因为和(5)不大于 10。

调用函数并捕获输出

在这一步中,你将学习如何在 Python 中调用函数并捕获其输出。捕获函数的输出能让你在脚本中使用返回值进行进一步的计算或操作。

我们将继续使用上一步中的 calculate_sum.py 文件。如果你还未完成上一步,请创建包含以下内容的文件:

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)

现在,让我们修改脚本,以捕获 calculate_sum 函数的输出,并对其进行额外的操作。

  1. 在 VS Code 编辑器中打开 calculate_sum.py 文件。

  2. 按如下方式修改脚本:

    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)

    在这个修改后的脚本中:

    • 我们使用 num1num2 调用 calculate_sum 函数,并将返回值存储在 result 变量中。
    • 然后,我们将 result 加上 20,并将结果存储在 final_result 中。
    • 最后,我们打印 final_result 的值。
    • 我们还使用 num3num4 调用 calculate_sum 函数,并将返回值存储在 result2 变量中。
    • 然后,我们将 result2 乘以 2,并将结果存储在 final_result2 中。
    • 最后,我们打印 final_result2 的值。
  3. 使用以下命令运行脚本:

    python ~/project/calculate_sum.py

    你应该会看到以下输出:

    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

    这个输出表明,你可以成功调用函数、捕获其返回值,并在脚本中使用该值进行后续操作。

将输出与预期值进行比较

在这一步中,你将学习如何将函数的输出与预期值进行比较。这是测试和确保函数正常工作的关键部分。通过将实际输出与预期输出进行比较,你可以识别并修复代码中的任何错误。

我们将继续使用前几步中的 calculate_sum.py 文件。如果你还未完成前几步,请创建包含以下内容的文件:

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)

现在,让我们添加一个函数来将输出与预期值进行比较,并打印一条消息,表明测试是通过还是失败。

  1. 在 VS Code 编辑器中打开 calculate_sum.py 文件。

  2. 按如下方式修改脚本:

    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)

    在这个修改后的脚本中:

    • 我们定义了一个名为 compare_output 的函数,它接受两个参数:actual_outputexpected_output
    • 在函数内部,我们将 actual_outputexpected_output 进行比较。
    • 如果它们相等,我们打印 "Test passed!"。
    • 如果它们不相等,我们打印 "Test failed." 以及预期值和实际值。
    • 然后,我们使用 final_resultexpected_final_result 调用 compare_output 函数,将第一次计算的输出与预期值 50 进行比较。
    • 我们还使用 final_result2expected_final_result2 调用 compare_output 函数,将第二次计算的输出与预期值 10 进行比较。
  3. 使用以下命令运行脚本:

    python ~/project/calculate_sum.py

    你应该会看到以下输出:

    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!

    这个输出表明,你可以成功地将函数的输出与预期值进行比较,并确定测试是通过还是失败。

总结

在本次实验中,第一步着重于理解 Python 中的函数返回值。这包括创建一个 calculate_sum.py 脚本,该脚本定义了一个名为 calculate_sum(x, y) 的函数,用于计算两个输入数字的和,并使用 return 语句返回结果。然后,脚本使用示例值调用此函数,并将返回的和打印到控制台,展示了函数如何返回一个可以被捕获并在代码其他地方使用的值。

随后,初始脚本被修改为根据条件返回不同的值,进一步说明了函数返回值的灵活性。这一步强化了函数作为可重用代码块的概念,这些代码块可以根据其输入和内部逻辑提供特定的输出。