How to return an object from a function in Python?

PythonServer Side ProgrammingProgramming

The return statement makes a python function to exit and hand back a value to its caller. The objective of functions in general is to take in inputs and return something. A return statement, once executed, immediately halts execution of a function, even if it is not the last statement in the function.

Functions that return values are sometimes called fruitful functions.

Example

def sum(a,b):
     return a+b
sum(5,16)

Output

21

Everything in python, almost everything is an object. Lists, dictionaries, tuples are also python objects. The code below shows a python function that returns a python object; a dictionary

Example

# This function returns a dictionary
def foo():
     d = dict();
     d['str'] = "Tutorialspoint"
     d['x']   = 50
     return d
print foo()

Output

{'x': 50, 'str': 'Tutorialspoint'}


raja
Published on 24-Jan-2018 07:33:14
Advertisements