When to return what, and how
Topics Covered in This Article
Defining Functions
Function definition starts with keyword def followed by the function name and a parenthesized list of formal parameters. The statements that form the body of the function start at the next line and must be indented.
def fname(parameters):
statement(s)
The function may contain return or yield statements.
If a function has a yield statement, it is known as a generator function.
The ‘return’ Statement
The return statement terminates the function call and returns a value to the caller.
The return statement without an expression argument returns None, and a function without a return statement also returns None.
Syntax:
"return" [expresion_list]
1. Return Type Is None
Example 1:
If there is no return statement inside the functions, it returns None.
def add(): pass print(add()) #Output:None
Example 2:
If the return statement is not reached in the function, it returns None.
Here, in this example, the condition c>10 is not satisfied, so it returns None.
def add(a,b):
c=a+b
if c>10:
return c
print(add(1,2))
#Output:None
Example 3:
def add(a,b): c=a+b print(add(1,2)) #Output:None
2. Returning multiple values from a function
Returning multiple values using commas
If the expression list in the return statement contains at least one comma, except when part of a list or set display, it returns a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.
The return type is a tuple.
def add(a,b): result=a+b return a,b,result print(add(1,2)) #Output:(1,2,3)
The return statement having a single expression with a trailing comma returns a tuple.
def add(a,b): result=a+b return result, print(add(1,2)) #Output:(3,)
Returning multiple values using list displays
A list display yields a new list object, the contents being specified by a list of expressions. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and placed into the list object in that order. The return type is a list.
def calc(a,b):
sum=a+b
dif=a-b
mul=a*b
div=a/b
return [sum,dif,mul,div]
print(calc(5,4))
#Output:[9, 1, 20, 1.25]
Returning multiple values using dictionary displays
A dictionary display yields a new dictionary object. When a comma-separated sequence of expressions in the key/value pairs is supplied, each key object is used as a key into the dictionary to store the corresponding value.
Return type is a dictionary.
def calc(a,b):
sum=a+b
dif=a-b
mul=a*b
div=a/b
return {"Addition":sum,"Subtraction":dif,"Multiplication":mul,"Division":div}
print(calc(5,4))
#Output:{'Addition': 9, 'Subtraction': 1, 'Multiplication': 20, 'Division': 1.25}
Returning multiple values using set displays
A set display yields a new mutable set object, the contents being specified by either a sequence of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and added to the set object. The return type is a set.
def calc(a,b):
sum=a+b
dif=a-b
mul=a*b
div=a/b
return {sum,dif,mul,div}
print(calc(5,4))
#Output:{9, 20, 1, 1.25}
3. Returning a single value from a function
The return statement having a single expression without a trailing comma doesn’t create a tuple; it returns the value of that expression.
def add(a,b):
result=a+b
return result
print(add(1,2))
#Output:3
print(add("Hello ","Python"))
#Output:Hello Python
print(add([1,2],[3,4]))
#Output:[1, 2, 3, 4]
print(add((1,2),(3,4)))
#Output:(1, 2, 3, 4)
4. Multiple ‘return’ statements in a single function
The function call is terminated when one of the return statements is reached.
def num(a):
if a%2==0:
return "Even Number"
else:
return "Odd Number"
print(num(5))#Output:Odd Number
print(num(30))#Output:Even Number
5. ‘return’ vs. ‘print’ statements inside a function
The return statement will terminate the function call and return the value to the caller.
The print statement will just print the value. We can’t assign that result to another variable or pass the result to another function.
Example: Assigning return value to a variable and also passing as an argument to another function
def add(a,b):
r1=a+b
return r1
def sub(c,d):
r2=c-d
return r2
#We can assign the return value to a variable r3=add(3,4) print(r3)#Output:7
#We can pass the return value to another function also. print(sub(r3,5))#Output:2
Example: Functions with the print statement
def add(a,b):
r1=a+b
print (r1)
add(3,4) #Output:7
#We can't assign the return value to a variable
r3=add(3,4)
print(r3)#Output:None
6. ‘return’ statement terminates the function call
The return statement terminates the current function call with the expression list (or None) as the return value. The statements after the return statement inside the function are not executed.
def add(a,b):
result=a+b
return result
print("After return statement")
print(add(3,4) )#Output:7
In the above example, the return statement will terminate the function call, so the print statement is not executed.
def add(a,b):
result=a+b
print(result)
print("Addition is done")
add(3,4)
'''
Output:
7
Addition is done
'''
In the above example, both the print statements are executed.
7. ’return’ statement in ‘try’ block
“When
returnpasses control out of atrystatement with afinallyclause, thatfinallyclause is executed before really leaving the function.” — Python documentation
Example: In the below example, the function call will return after executing the finally clause.
def add(a,b):
try:
result=a+b
return result
except Exception as e:
return e
finally:
print("Finally done")
print(add(3,4))
'''
Output:
Finally done
7
'''
If an exception is raised, the function call will return after executing the finally clause.
def add(a,b):
try:
result=a+b
return result
except Exception as e:
return e
finally:
print("Finally done")
print(add({'a':1},{'b':2}))
'''
Output:
Finally done
unsupported operand type(s) for +: 'dict' and 'dict'
'''
Conclusion
- The
returnstatement occurs only inside a function definition. - The
returnstatement will terminate the function call and returns the value. - The
returnstatement can return multiple values also. Thereturnvalue can be used as an argument to another function also. - If the
returnstatement is not in the function or if it is not reached, it will returnNone. - The function can have multiple
returnstatements also. The function call is terminated when one of thereturnstatements is reached.
I hope that you have found this article helpful. Thanks for reading!
My other blog links
5 Types of Arguments in Python Function Definition
Resources (Python Documentation):
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee