The return
statement in Python is used to exit a function and send a value or object back to the caller. It marks the end of the function’s execution and specifies what the function will output.
Syntax
def function_name(parameters):
# code
return value
return value
: Specifies the value or object to return to the caller.- If no
return
statement is used, the function returnsNone
by default.
Key Points
- Returning a Value: A function can return a single value, a list, a tuple, or any other data structure.
def add(a, b): return a + b result = add(3, 4) print(result) # Output: 7
- Multiple Return Values: Python allows returning multiple values by separating them with commas. These are returned as a tuple.
def calculate(a, b): return a + b, a - b, a * b result = calculate(5, 3) print(result) # Output: (8, 2, 15)
- Returning Nothing: If no
return
is used orreturn
is called without a value, the function returnsNone
.def greet(): print("Hello") result = greet() print(result) # Output: None
- Using
return
to Exit a Function Early: Areturn
statement can be used to terminate a function before it reaches the end.def check_positive(num): if num > 0: return "Positive" return "Not Positive" print(check_positive(5)) # Output: Positive print(check_positive(-3)) # Output: Not Positive
Example Use Cases
- Return a Calculated Result:
def square(num): return num ** 2 print(square(4)) # Output: 16
- Return Conditional Values:
def check_even(num): return "Even" if num % 2 == 0 else "Odd" print(check_even(7)) # Output: Odd
- Return a Complex Data Structure:
def get_user_data(): return {"name": "Alice", "age": 30} user = get_user_data() print(user["name"]) # Output: Alice
Best Practices
- Always use
return
to explicitly indicate what a function should output. - Avoid unnecessary
return
statements unless they add clarity or functionality. - Use meaningful return values that make the function’s purpose clear.
The return
statement is a fundamental tool in Python for building reusable and modular code.