29. Using the return statement in Python Functions

Quiz: 0/5

In Python, the return statement is used within functions to send back values to the caller. This is essential for modular and reusable code, as functions can compute results and return them to be used elsewhere in the program.

Purpose of the return statement

The return statement allows a function to output a value, which can then be used for further processing, calculations, or stored in a variable. When the return statement is executed, the function immediately stops, and control is returned to the point where the function was called.

Any code after the return statement will not be executed.

Example: Simple return

def add(a, b):
    result = a + b  # Calculate the sum
    return result  # Return the result to the caller

sum_value = add(3, 5)  # Calling the function and storing the result
print("The sum is:", sum_value)  # Output: The sum is: 8

Explanation:

  • The add(a, b) function takes two parameters, a and b.
  • It calculates their sum and uses the return statement to send this result back to the caller.
  • The returned value is stored in sum_value, which is then printed.

Returning multiple values

Python allows functions to return multiple values at once using tuples. This is useful when you want to send back more than one result.

Example: Returning multiple values

def arithmetic_operations(x, y):
    addition = x + y
    subtraction = x - y
    return addition, subtraction  # Returning both values as a tuple

result_sum, result_difference = arithmetic_operations(10, 4)  # Unpacking the returned tuple
print("Sum:", result_sum)          # Output: Sum: 14
print("Difference:", result_difference)  # Output: Difference: 6

Explanation:

  • The function arithmetic_operations(x, y) calculates both the sum and the difference of x and y.
  • It returns these two values as a tuple.
  • The caller unpacks the tuple into two variables, result_sum and result_difference, and prints them.

Implicit return

If a function does not include a return statement, Python automatically returns None. This behavior can be useful when you want to create a function that only performs an action without returning a value.

Example: Implicit return

def no_return():
    print("This function has no return statement.")

result = no_return()  # Calling the function
print(result)  # Output: None

Explanation:

  • The function no_return() prints a message but does not have a return statement.
  • By default, it returns None, which is captured by the variable result.

Return vs. Print

While the print() function outputs a value to the console, the return statement sends a value back to the caller for further use. It's important to know the difference because print() is used for displaying information, while return is used to provide output that can be used later in the program.

Example: Return vs Print

def double(x):
    print("Doubling:", x * 2)  # Prints the doubled value
    return x * 2  # Returns the doubled value

result = double(5)
print("Returned value:", result)  # Output: Returned value: 10

Explanation:

  • The function double(x) both prints the doubled value and returns it.
  • The return value is stored in result, while the print statement shows the value during the function's execution.

Summary

The return statement is fundamental in Python functions. It allows a function to output values that can be used elsewhere, making code more modular and reusable. Key points include:

  • Single Return Value: A function can return a single value, such as the result of a calculation.
  • Multiple Return Values: A function can return multiple values as a tuple.
  • Implicit Return: If no return statement is provided, Python returns None by default.
  • Difference with print(): The return statement provides values for further use, while print() is used for displaying information.

Hands-On Practise

Exercise: Creating a simple calculator function

Write a Python function called calculator that performs basic arithmetic operations (addition, subtraction, multiplication, and division). The function should take two numbers as input and return the results of all four operations as a tuple.

Your function should work as follows:

  1. It should accept two parameters: num1 and num2.
  2. It should return a tuple containing:
    • The sum of num1 and num2
    • The difference num1 - num2
    • The product num1 * num2
    • The quotient num1 / num2 if num2 is not zero. If num2 is zero, return "Cannot divide by zero" for the quotient.

Guidelines:

  1. Use the return statement to send back the results.
  2. Handle the case where division by zero might occur.
Output:

Quizzes: 0/5

Question 1:

What does the return statement do in a Python function?

  • It stops the function execution and sends a value back to the caller.
  • It prints a value to the console.
  • It only modifies global variables.
  • It stops the program execution.

Question 2:

What happens if a function in Python does not have a return statement?

  • The function will raise an error.
  • The function will return None by default.
  • The function will return an empty string.
  • The function will exit without performing any action.

Question 3:

How can a Python function return multiple values?

  • By using a list.
  • By using a tuple.
  • By using multiple return statements.
  • By using global variables.

Question 4:

What is the result if division by zero occurs in the function below? `python def calculator(num1, num2): if num2 != 0: return num1 / num2 else: return 'Cannot divide by zero' `

  • The function will return infinity.
  • The function will return None.
  • The function will return 'Cannot divide by zero'.
  • The function will raise an exception.

Question 5:

In which of the following cases will the function return a tuple?

  • When the function has multiple return statements.
  • When the function returns more than one value on the same line.
  • When the function prints multiple values.
  • When the function modifies global variables.

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonNested Functions and Nonlocal variablesNext lessonLambda Functions in Python