Skip to main content
Published on

return in Python

Share:

Introduction

The return statement is an integral part of functions in Python. It not only marks the end of a function's execution but also allows values to be sent back to where the function was called. In this article, we'll explore the ins and outs of how and when to use return.

The Purpose of return

  • When we use return, we are essentially telling the function to send a value back to the point where it was called.
  • With it, you can perform calculations or process data inside a function and then use that result in other parts of the program.

Basic Example of return

def square(number):
  return number * number

result = square(5)
print('The square of 5 is:', result)  # The square of 5 is: 25

Functions Without return

Not all functions need a return statement. Some functions are used only to execute a series of commands and do not need to return any value.

def greeting(name):
  print('Hello,', name + '!')

greeting('Maria')  # Hello, Maria!

However, if we try to assign the result of this function to a variable, we would receive a None value, since the function has no return statement.

Returning Multiple Values

In Python, it is possible to return multiple values from a function using tuples.

def calculations(a, b):
  total = a + b
  difference = a - b
  product = a * b
  return total, difference, product

res_total, res_diff, res_prod = calculations(10, 5)
print('Sum:', res_total, 'Difference:', res_diff, 'Product:', res_prod)

Conclusion

The return statement significantly expands the capabilities of functions in Python. It not only allows functions to be more versatile by returning values to be used elsewhere in the code, but also facilitates the creation of cleaner and more modular code.

Happy coding!