Returning Value in Function
-
This lesson teaches how to return output values from functions in Python.
What is Return Value in a Function?
A return value is the data that a function sends back to the caller after completing its task.
👉 The return keyword is used to send values from a function.
Why Do We Use return?
We use return to:
Get results from a function
Store function output in variables
Reuse function results
Perform further operations
Improve modular programming
Syntax of return
def function_name():
return value
What is Returning a Single Value?
When a function sends only one value, it is called returning a single value.
Returning a Single Value
This function calculates the square of a number and returns the result.
def square(num):
return num * num
result = square(5)
print("Square:", result)
How Python Returns Multiple Values?
Python returns multiple values using a tuple (packing).
👉 Even though it looks like multiple values, Python actually returns one tuple.
Syntax
def function_name():
return value1, value2
Returning Multiple Values
This function returns sum and difference of two numbers.
def calculate(a, b):
return a + b, a - b
result = calculate(10, 5)
print(result)
Returning Different Data Types
This function returns a name and age together.
def user_info():
return "Ravi", 22
name, age = user_info()
print(name, age)
Returning a List
This function returns a list of even numbers.
def even_numbers():
return [2, 4, 6, 8]
nums = even_numbers()
print(nums)
Returning a Dictionary
This function returns student details as a dictionary.
def student():
return {"name": "Neha", "age": 21}
info = student()
print(info)
Important Rules of return
A function can have multiple return statements, but only one executes
return without value returns None
Multiple values are returned as a tuple
Code after return does not execute