Python Function Return Types

In today’s tutorial, I will explain everything on Python function return types. You will learn how function return types work.

In Python, a function’s return type is determined by the value it returns using the return statement. For example, if a function returns the sum of two integers, its return type is an integer. Here’s a simple example:

def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8

In this case, the add function returns an integer, which is the sum of a and b.

What is a Python Function Return Type?

In Python, a function can return a value using the return statement. The return type of a function is the type of value that the function returns. This is crucial because it helps you understand what kind of data you can expect from a function, which in turn aids in debugging and maintaining your code.

Syntax of Return Statement

The syntax for the return statement in Python is:

def function_name(parameters):
    # function body
    return expression

Here, the expression is evaluated and returned as the output of the function. If no expression is given, the function returns None by default.

Unlike some other programming languages, Python does not explicitly declare a function’s return type. Instead, it is inferred from the value returned. This dynamic typing feature makes Python flexible but also necessitates careful documentation and testing to ensure that functions behave as expected.

Check out How to Call a Function by String in Python?

Examples of Python Function Return Types

Now, let me show you some examples of Python function return types.

Return a Single Value

Here is a simple example that returns a single value in a Python function.

def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8

In this example, the add function returns an integer, which is the sum of a and b.

Here you can see the output in the screenshot below:

Python Function Return Types

Return Multiple Values

Python allows functions to return multiple values as tuples. Here is an example.

def get_name_and_age():
    name = "John"
    age = 30
    return name, age

name, age = get_name_and_age()
print(name)  # Output: John
print(age)   # Output: 30

Here, the function get_name_and_age returns a tuple containing a string and an integer.

Here is the output in the screenshot below:

python functions return type

Check out How to Call the Main Function in Python?

Return Lists and Dictionaries

Functions can also return more complex data structures like lists and dictionaries. Let me show you an example.

def get_fruits():
    return ["apple", "banana", "cherry"]

fruits = get_fruits()
print(fruits)  # Output: ['apple', 'banana', 'cherry']

def get_student_scores():
    return {"John": 90, "Jane": 85, "Doe": 88}

scores = get_student_scores()
print(scores)  # Output: {'John': 90, 'Jane': 85, 'Doe': 88}

Conditional Return Types

Sometimes, the return type of a function can vary based on conditions. Below is the complete Python example and code.

def check_number(num):
    if num > 0:
        return "Positive"
    elif num < 0:
        return "Negative"
    else:
        return 0

print(check_number(10))  # Output: Positive
print(check_number(-5))  # Output: Negative
print(check_number(0))   # Output: 0

In this scenario, the function check_number can return either a string or an integer.

I executed the above Python code, and you can see the output in the screenshot below:

Return Type for Python Function

Using Type Hints for Clarity

To make your code more readable and maintainable, you can use type hints introduced in Python 3.5:

from typing import Union

def check_number(num: int) -> Union[str, int]:
    if num > 0:
        return "Positive"
    elif num < 0:
        return "Negative"
    else:
        return 0

print(check_number(10))  # Output: Positive

Here, Union[str, int] indicates that the function can return either a string or an integer.

Check out Run a Python Function from the Command Line

Return Functions

In Python, functions are first-class citizens, meaning they can be returned from other functions. Here is an example.

def outer_function():
    def inner_function():
        return "Hello from the inner function!"
    return inner_function

returned_function = outer_function()
print(returned_function())  # Output: Hello from the inner function!

This scenario is particularly useful for decorators and higher-order functions.

Here is the output in the screenshot below:

Return Type for Python Functions

Conclusion

I hope now you understand everything about Python function return types. By knowing what kind of data a function returns, you can make your code more predictable and easier to debug. Whether it’s a single value, multiple values, or even another function, mastering return types will undoubtedly make you a more proficient Python programmer.

So, experiment with different return types in your Python projects. If you still have questions, comment below.

You may also like:

Leave a Comment