Lightning bolt and Python code snippet with "PYTHON RETURN" in blocky caps

Keyword return Python Ultimate Guide

In Python, the return keyword is essential when working with functions. It is used to exit a function and return a value or result to the caller. To do the return Python functions use the built-in keyword, ‘return’.

By the end of this guide, you’ll have a thorough understanding of how to use the return keyword in Python effectively.

What is the return Keyword in Python?

The return keyword in Python is used in a function to:

  1. Exit the function: Once Python encounters the return keyword, it immediately stops executing the rest of the function.
  2. Return a value: The value following the return keyword is sent back to the function’s caller, allowing you to pass data from the function back to the code that called it.

Syntax of return:

def function_name(parameters):
    # function logic
    return value
  • value: The value or object you want to return. It can be any Python object (numbers, strings, lists, dictionaries, etc.).

Example of return:

def add_numbers(a, b):
    result = a + b
    return result

# Calling the function
sum_value = add_numbers(3, 4)
print(sum_value)  # Output: 7

In this example, the return keyword sends the result of the addition (7) back to where the function was called, allowing it to be printed.

Why is the return Keyword Important?

The return keyword is essential because it allows functions to:

  • Output data: Functions are often used to perform calculations or process data. Without return, there is no way to get the result back.
  • Terminate function execution: return can be used to end a function’s execution early, which is useful when certain conditions are met.
  • Return multiple values: Python allows you to return multiple values from a function, which makes it powerful for passing multiple pieces of data.

Using return to Pass Values From a Function

In Python, a function can return a value or result by following the return keyword with the desired value. The value can then be stored in a variable, used in an expression, or passed to other functions.

Example: Returning a Value

def square(number):
    return number ** 2

result = square(5)
print(result)  # Output: 25

In this example, the function square() returns the square of the input value. The value 25 is returned and stored in the variable result.

Returning Multiple Values in Python

Python allows functions to return multiple values by separating them with commas. The values are returned as a tuple, which can then be unpacked or used directly.

Example: Returning Multiple Values

def get_coordinates():
    x = 10
    y = 20
    return x, y

x_coord, y_coord = get_coordinates()
print(x_coord)  # Output: 10
print(y_coord)  # Output: 20

In this example, the function get_coordinates() returns two values (x and y), which are unpacked into the variables x_coord and y_coord.

Difference Between return and print()

It’s important to understand the difference between return and print() in Python. While both can output values, they serve different purposes:

  • return: Sends a value back to the function’s caller and exits the function. The returned value can be stored in a variable, used in an expression, or passed to other functions.
  • print(): Outputs a value to the console, but it does not return anything. It is mainly used for debugging or displaying information to the user.

Example:

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

def print_add(a, b):
    print(a + b)

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

# Using print
print_add(5, 3)  # Output: 8

In the first function (add()), the result is returned, and you can store it in a variable or use it later. In the second function (print_add()), the result is displayed immediately, but you cannot reuse the result elsewhere.

Returning None in Python

By default, if a function does not have an explicit return statement, it implicitly returns None. None is a special value in Python representing the absence of a value.

Example:

def no_return():
    pass

result = no_return()
print(result)  # Output: None

In this example, the function no_return() does not have a return statement, so Python automatically returns None.

Returning None Explicitly:

You can also explicitly return None when you want to signal that no meaningful value is being returned.

Example:

def check_number(number):
    if number > 10:
        return number
    else:
        return None

result = check_number(5)
print(result)  # Output: None

Using return to Exit a Function Early

You can use return to exit a function early if certain conditions are met. This is particularly useful when you only want to return a result if certain criteria are satisfied.

Example: Early Exit With return

def check_even(number):
    if number % 2 == 0:
        return True
    return False

result = check_even(4)
print(result)  # Output: True

In this example, if the number is even, the function returns True immediately and skips the rest of the code.

Best Practices for Using return in Python

  1. Always Use return to Output Data: Use the return keyword to send the result of a function back to the caller, allowing the function’s result to be stored or used in other expressions.
  2. Return Early When Appropriate: If certain conditions allow you to conclude the function’s work early, use return to exit the function and avoid unnecessary calculations.
  3. Return Multiple Values as a Tuple: If your function needs to return multiple values, use commas to separate them. Python will return these values as a tuple, which you can unpack later.
  4. Avoid Using print() for Function Outputs: While print() is useful for debugging or displaying information, it should not be used as a substitute for return. Use return to output values from a function and store or reuse the result.
  5. Explicitly Return None When No Value Is Required: If your function doesn’t need to return a value, consider explicitly returning None to indicate that the function has no result.

Common Mistakes When Using return

  1. Forgetting to Use return: If you forget to use return in your function, Python will automatically return None, which may lead to unintended behavior.

Example:

def add_numbers(a, b):
    result = a + b  # No return statement

result = add_numbers(3, 4)
print(result)  # Output: None
  1. Using print() Instead of return: Beginners often confuse print() and return(). print() only displays a value but doesn’t return it for further use.
  2. Not Handling Multiple Return Values Properly: If a function returns multiple values, ensure that you unpack them correctly or handle them as a tuple.

Summary of Key Concepts

  • The return keyword is used to exit a function and send a value back to the caller.
  • return can return any Python object, including numbers, strings, lists, and more.
  • Functions can return multiple values, which are packed into a tuple.
  • None is returned by default if a function does not have a return statement.
  • Use return for reusable results and print() for debugging or displaying values.
  • return can also be used to exit a function early if certain conditions are met.

Exercises

  1. Basic Return Function: Write a function that takes two numbers as arguments, adds them together, and returns the result.
  2. Returning Multiple Values: Write a function that takes a string as input and returns the string’s length and the string itself in uppercase.
  3. Early Exit: Write a function that checks if a number is negative. If it is, return "Negative", otherwise return "Positive".
  4. Handling None: Write a function that takes a list of numbers and returns the first even number. If no even number is found, return None.
Lightning bolt and Python code snippet with "LEARN PYTHON PROGRAMMING MASTERCLASS" in blocky caps

Check out our FREE Learn Python Programming Masterclass to hone your skills or learn from scratch.

The course covers everything from first principles to Graphical User Interfaces and Machine Learning

Browse the official Python documentation on the return statement here.

FAQ

Q1: Can a Python function have more than one return statement?

A1: Yes, a Python function can have multiple return statements. Once Python encounters a return statement, it immediately exits the function and returns the specified value. You can use multiple return statements in different parts of the function to handle different conditions.

Example:

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

print(check_number(5))  # Output: Positive

Q2: What happens if I don’t include a return statement in a function?

A2: If a function doesn’t include a return statement, it implicitly returns None. This is the default behavior in Python, so if you forget to use return, the function will still return None, which might lead to unintended results.

Example:

def no_return_function():
    pass  # No return statement

result = no_return_function()
print(result)  # Output: None

Q3: Can I return more than one value from a Python function?

A3: Yes, you can return multiple values from a Python function by separating them with commas. The values are returned as a tuple, which you can unpack or handle as needed.

Example:

def get_person_info():
    name = "Alice"
    age = 30
    return name, age

name, age = get_person_info()
print(name)  # Output: Alice
print(age)   # Output: 30

Q4: What is the difference between return None and just using return?

A4: Both return None and using return without specifying a value will return None, but there’s a slight difference:

  • return None explicitly tells the reader that the function is returning None.
  • return without a value implicitly returns None, but it’s less clear to the reader that None is being returned.

Example:

def explicit_none():
    return None

def implicit_none():
    return

print(explicit_none())  # Output: None
print(implicit_none())  # Output: None

Q5: Can I return a function itself using the return keyword?

A5: Yes, you can return a function (or a reference to a function) using the return keyword. This is commonly used in higher-order functions, which are functions that return other functions.

Example:

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

func = outer_function()
print(func())  # Output: Hello from inner function

Q6: Can return be used outside a function?

A6: No, the return statement is specifically designed to be used inside a function. If you try to use return outside a function, Python will raise a SyntaxError.

Example:

return 5  # Raises SyntaxError: 'return' outside function

Q7: What happens if a function has code after a return statement?

A7: Any code that comes after a return statement inside a function is ignored because the return statement immediately exits the function. It is good practice to avoid writing unnecessary code after a return statement.

Example:

def sample_function():
    return "Returned value"
    print("This will never be printed")  # This line is ignored

print(sample_function())  # Output: Returned value

Q8: Can I use return inside loops or conditionals?

A8: Yes, you can use return inside loops and conditionals within a function. The return statement will exit the function as soon as it’s encountered, even if it is inside a loop or conditional block.

Example:

def find_first_even(numbers):
    for num in numbers:
        if num % 2 == 0:
            return num  # Exits the function and returns the first even number
    return None  # If no even number is found

print(find_first_even([1, 3, 5, 8, 11]))  # Output: 8

Q9: Can I return different data types from the same function?

A9: Yes, Python functions are flexible and can return different data types based on conditions. For example, a function might return a string in one case and a list in another.

Example:

def process_data(data):
    if isinstance(data, list):
        return len(data)
    elif isinstance(data, str):
        return data.upper()
    return None

print(process_data([1, 2, 3]))  # Output: 3
print(process_data("hello"))    # Output: HELLO

Q10: Can a function return another function and its result at the same time?

A10: Yes, you can return a function and call it within the same return statement. However, keep in mind that once the function is called, the returned result will be whatever the inner function returns, not the function itself.

Example:

def outer_function():
    def inner_function():
        return "Result from inner function"
    return inner_function()

print(outer_function())  # Output: Result from inner function

Similar Posts