Python return Statement

Python provides the return statement in order to return some value, data, or object at the end of function execution. The return statement is used to provide the execution result to the caller. The return statement can not be used outside of a function that makes the return statement function specific. In this tutorial, we examine how the return statement can be used for different cases.

return Statement Syntax

The return statement has a different syntax where it can be only used inside a function. This means the return statement can not be used outside of a function like inside an object or python script.

def function():
   ...
   BODY
   ...
   return EXPRESSION
  • BODY is the function body where different statements are provided which will be executed inside functions.
  • EXPRESSION is the expression which result will be returned to the function caller. EXPRESSION can be a value, object, varible, list etc. even it can be function too.

Return Value

The return statement is generally used to return a value. One of the most popular reasons to use and call a function is making some calculations or actions and result in some value. The return statement can return values or variable values easily like below. In the following example, we return the sum of the two parameters provided to the function.

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

returned_result = sum(1,2)

Return Object

The return statement can also return the object as to the function caller.

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

returned_result = sum(1,2)

Return List

The return statement can be used to return multiple items. One way is using a list where multiple items can be put inside a list and return this list to the function caller.

def say(a,b):
   names = ["ahmet","ali","baydan"]
   return names

returned_list = say()

Return Multiple Values and Objects with Tuple

A tuple is a comma-separated sequence of items and a tuple can not be changed after creation. Simple a tuple is immutable. A tuple can be used with the return statement in order to return multiple items.

def say(a,b):
   print("Returning a tuple")
   return "ahmet","ali",1

returned_list = say()

Return Function

The return statement can be also used as a return function. The function can be defined inside another function and the inner function name can be provided to the return statement. The returned function can be used as a regular function.

def math():
   def sum(a,b):
      return a+b
   
   return sum


mysum=math()

result = mysum(1,2)

Leave a Comment