Python 3 Tutorial
return statement can be used to a pass control back to the caller or value from any Python function.
Python return statement without a value return None Type .
Python return statement return any valid type data to the caller
def Nothing(): passCall Nothing function and assign return value to a variable
ret = Nothing() type(ret) <class 'NoneType'>Programatically you can check return type using is operator
>>> ret is None TrueLet's modify Nothing Function, add return statement after pass, and then add print statement.
>>> def Nothing(): pass return print("After return") >>>Nothing()
pass is nothing but a null statement. return statement after pass, will return control back to the caller. so that finished execution of function Nothing(). What about print statement after return statement, control already passed back to the caller,it becomes unreachable code. Function never execute print statement
Python function can return List,Set,Dictionary,String etc.,
Following function mylist takes one object, that should be a sequence. "Alphabets" string object supports iteration,so it can be passed to list constructor
def mylist(obj): return list(obj) #Calling above function newList = mylist("Alphabets") type(newList) <class 'list'> print(newList) ['A', 'l', 'p', 'h', 'a', 'b', 'e', 't', 's']Let's Add Exception Handling to above function. obj argument is iteratable, list with object values returned. if obj is not iteratable(int, float) values, function returns empty list , as shown below.
def mylist(obj): try: return list(obj) except Exception as e: return list() newList = mylist("Alphabets") print(newList) ['A', 'l', 'p', 'h', 'a', 'b', 'e', 't', 's'] newList = mylist(123) print(newList) []Let's write Another Function which returns Dictionary Data type. Dictionary maintains key value pair, In this example collecting personal details key is a string object, value can be any type.
def getDetails(): return {'Name':'Sam', 'Age':34, 'DOB':1973, 'hasJob':False, 'Monthly_Income':20000 } d=getDetails() print(type(d)) print(d) #OUTPUT <class 'dict'> {'Name': 'Sam', 'Age': 34, 'DOB': 1973, 'hasJob': False, 'Monthly_Income': 20000}
Programatically user can check whether variable 'd' is dictionary object or not. isinstance(d, dict) returns boolean value True
In Python return type checked the value it returned, you cannot specify return type explicitely.import random def pickup(): return random.choice([1, 2, 3.33333, 4.55555, 10.999,'jhon peter'])Everytime you call , it returns different Datatype value. because it is a random choice function, list has all types of data i.e int,float and string, randomly picking one element at a time.
>>> pickup() 1 >>> pickup() 3.33333 >>> pickup() 1 >>> pickup() 'jhon peter' >>> pickup() 2 >>> pickup() 1 >>> pickup() 1 >>> pickup() 10.999 >>> pickup() 10.999 >>> pickup() 10.999 >>> pickup() 4.55555 >>>
ADS