Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to return an object from a function in Python?
In Python, functions can return objects of any type using the return keyword. This includes simple values, complex data structures, and custom objects.
The statements after the return will not be executed. The return keyword cannot be used outside a function. If a function has a return statement without any expression, the special value None is returned.
Returning Simple Values
Here's a basic example of returning a calculated value ?
def sum_numbers(a, b):
return a + b
my_var1 = 23
my_var2 = 105
result = sum_numbers(my_var1, my_var2)
print(result)
128
Return Value in Void Function
A function without an explicit return statement returns None. The pass keyword prevents IndentationError in empty functions ?
def empty_function():
pass
result = empty_function()
print("Return type of void function:", result)
print("Type:", type(result))
Return type of void function: None Type: <class 'NoneType'>
Returning Dictionary Objects
Functions can return complex data structures like dictionaries ?
def create_state_capitals():
capitals = {}
capitals['Telangana'] = 'Hyderabad'
capitals['Tamilnadu'] = 'Chennai'
capitals['Karnataka'] = 'Bangalore'
return capitals
state_dict = create_state_capitals()
print(state_dict)
print("Capital of Karnataka:", state_dict['Karnataka'])
{'Telangana': 'Hyderabad', 'Tamilnadu': 'Chennai', 'Karnataka': 'Bangalore'}
Capital of Karnataka: Bangalore
Returning Custom Objects
Functions can also return instances of custom classes ?
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def __str__(self):
return f"Student: {self.name}, Grade: {self.grade}"
def create_student(name, grade):
return Student(name, grade)
student_obj = create_student("Alice", "A+")
print(student_obj)
print("Student name:", student_obj.name)
Student: Alice, Grade: A+ Student name: Alice
Returning Multiple Objects
Python functions can return multiple objects as a tuple ?
def get_name_age():
return "John", 25
name, age = get_name_age()
print("Name:", name)
print("Age:", age)
# Or as a tuple
result = get_name_age()
print("Tuple result:", result)
Name: John
Age: 25
Tuple result: ('John', 25)
Conclusion
Python functions can return any type of object using the return keyword. Functions without explicit return statements return None. This flexibility makes Python functions powerful for data processing and object creation.
