Python 에서 함수가 특정 값을 반환하는지 확인하는 방법

PythonBeginner
지금 연습하기

소개

이 랩에서는 Python 함수가 특정 값을 반환하는지 확인하는 방법을 배우게 됩니다. 이 랩은 return 문을 사용하여 함수의 반환 값을 이해하고 출력을 검증하는 데 중점을 둡니다.

먼저 두 숫자의 합을 계산하고 결과를 반환하는 함수가 있는 Python 스크립트를 생성하는 것으로 시작합니다. 그런 다음 스크립트를 실행하고 출력을 관찰합니다. 마지막으로, 조건에 따라 다른 값을 반환하도록 스크립트를 수정하고 반환된 값을 확인합니다.

함수 반환 이해

이 단계에서는 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)

    이 코드에서:

    • 두 개의 인자 xy를 받는 calculate_sum이라는 함수를 정의합니다.
    • 함수 내부에서 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)

    여기서는 합계가 10 보다 큰지 확인하기 위해 조건문 (if sum_result > 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에 대한 첫 번째 호출은 합계 (15) 가 10 보다 크므로 두 배가 되어 30 을 반환합니다. 두 번째 호출은 합계 (5) 가 10 보다 크지 않으므로 5 를 반환합니다.

함수 호출 및 출력 캡처

이 단계에서는 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)

    이 수정된 스크립트에서:

    • num1num2calculate_sum 함수를 호출하고 반환된 값을 result 변수에 저장합니다.
    • 그런 다음 result에 20 을 더하고 final_result에 저장합니다.
    • 마지막으로 final_result의 값을 출력합니다.
    • 또한 num3num4calculate_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)

    이 수정된 스크립트에서:

    • actual_outputexpected_output의 두 인수를 사용하는 compare_output이라는 함수를 정의합니다.
    • 함수 내부에서 actual_outputexpected_output과 비교합니다.
    • 두 값이 같으면 "Test passed!"를 출력합니다.
    • 두 값이 같지 않으면 예상 값과 실제 값을 함께 "Test failed."를 출력합니다.
    • 그런 다음 final_resultexpected_final_resultcompare_output 함수를 호출하여 첫 번째 계산의 출력을 예상 값 50 과 비교합니다.
    • 또한 final_result2expected_final_result2compare_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!

    이 출력은 함수의 출력을 예상 값과 성공적으로 비교하고 테스트가 통과했는지 실패했는지 확인할 수 있음을 보여줍니다.

요약

이 Lab 에서는 첫 번째 단계에서 Python 의 함수 반환에 대해 중점적으로 다룹니다. calculate_sum.py 스크립트를 생성하여 calculate_sum(x, y) 함수를 정의합니다. 이 함수는 두 개의 입력 숫자의 합을 계산하고 return 문을 사용하여 결과를 반환합니다. 그런 다음 스크립트는 이 함수를 샘플 값으로 호출하고 반환된 합을 콘솔에 출력하여 함수가 코드의 다른 곳에서 캡처하고 사용할 수 있는 값을 반환하는 방법을 보여줍니다.

그런 다음 초기 스크립트를 수정하여 조건에 따라 다른 값을 반환하도록 하여 함수 반환의 유연성을 더욱 보여줍니다. 이 단계는 함수를 입력 및 내부 로직을 기반으로 특정 출력을 제공할 수 있는 재사용 가능한 코드 블록으로 개념을 강화합니다.