Returning from functions in Python


We can pass values into a function with arguments. You can use a return statement to send a value back out of a function.

The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to answer below):

def plusThree(num):
    return num + 3

answer = plusThree(5)

answer has the value 8.

plusThree takes an argument for num and returns a value equal to num + 3.


No return statement:

In the case that the function doesn't have a return statement, when you call it, the function processes the inner code but the returned value is None:

sum = 0

def addToSum(num):
    sum += num

returned = addToSum(3)

print(sum) # Output: 3
print(returned) # Output: None

addSum is a function without a return statement. The function will change the global sum variable but the returned value of the function is None.


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


Introduction

In this lesson, we will explore the concept of returning values from functions in Python. Understanding how to use the return statement is crucial for writing effective and reusable code. Functions that return values can be used in various scenarios, such as performing calculations, processing data, and more.

Understanding the Basics

At its core, a function in Python can take inputs (arguments) and produce an output using the return statement. The return statement allows a function to send a value back to the caller, which can then be used or stored as needed.

Consider the following simple example:

def multiplyByTwo(num):
    return num * 2

result = multiplyByTwo(4)
print(result)  # Output: 8

In this example, the function multiplyByTwo takes an argument num and returns the value of num * 2. The returned value is then stored in the variable result and printed.

Main Concepts

Let's delve deeper into the key concepts and techniques involved in returning values from functions:

Here is an example of a function returning multiple values:

def calculateSumAndProduct(a, b):
    sum_result = a + b
    product_result = a * b
    return sum_result, product_result

sum_value, product_value = calculateSumAndProduct(3, 4)
print(sum_value)  # Output: 7
print(product_value)  # Output: 12

In this example, the function calculateSumAndProduct returns two values: the sum and the product of the input arguments. These values are then unpacked into the variables sum_value and product_value.

Examples and Use Cases

Let's look at some more examples to understand the practical applications of returning values from functions:

# Example 1: Checking if a number is even
def isEven(num):
    return num % 2 == 0

print(isEven(4))  # Output: True
print(isEven(7))  # Output: False

# Example 2: Finding the maximum of two numbers
def findMax(a, b):
    if a > b:
        return a
    else:
        return b

print(findMax(10, 20))  # Output: 20
print(findMax(30, 15))  # Output: 30

In these examples, the functions isEven and findMax return boolean and integer values, respectively, based on the input arguments.

Common Pitfalls and Best Practices

When working with return statements, it's important to be aware of common pitfalls and follow best practices:

Advanced Techniques

Advanced techniques related to returning values from functions include using generators and decorators:

Here is an example of a generator function:

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for number in countdown(5):
    print(number)

In this example, the countdown function uses the yield statement to return values one at a time, allowing the caller to iterate over them.

Code Implementation

Let's implement a function that calculates the factorial of a number and returns the result:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

result = factorial(5)
print(result)  # Output: 120

In this implementation, the factorial function uses recursion to calculate the factorial of a number. The base case returns 1 when n is 0, and the recursive case multiplies n by the factorial of n - 1.

Debugging and Testing

When debugging and testing functions that return values, consider the following tips:

Here is an example of a simple unit test for the factorial function:

import unittest

class TestFactorial(unittest.TestCase):
    def test_factorial(self):
        self.assertEqual(factorial(5), 120)
        self.assertEqual(factorial(0), 1)
        self.assertEqual(factorial(3), 6)

if __name__ == '__main__':
    unittest.main()

Thinking and Problem-Solving Tips

When approaching problems related to returning values from functions, consider the following strategies:

Conclusion

In this lesson, we covered the importance of returning values from functions in Python. We explored the basics, key concepts, examples, common pitfalls, advanced techniques, and best practices. Mastering the use of return statements will enable you to write more effective and reusable code.

Keep practicing and exploring further applications to deepen your understanding of this fundamental concept.

Additional Resources