The return Statement
Most functions perform calculations or fetch data and need to send a result back to the place where they were called. The return statement is used for this.
- When
returnis executed, the function immediately stops execution. - The value following
returnis sent back to the caller. - If a function doesn't explicitly
returna value, it implicitly returns the special valueNone.
Example: Calculating Area
python def calculate_area(length, width): if length <= 0 or width <= 0: return "Invalid dimensions"
area = length * width
return area # Returns the calculated value
Call the function and store the result in a variable
room_area = calculate_area(5, 8) print(f"The room area is: {room_area}") # Output: 40
Example of early return
error_area = calculate_area(-2, 5) print(error_area) # Output: Invalid dimensions
Returning Multiple Values
Python functions can appear to return multiple values. In reality, they return a single tuple containing the values, which can then be unpacked by the caller.
python def get_stats(data): # Calculates minimum and maximum return min(data), max(data)
Tuple unpacking on the receiving end
min_val, max_val = get_stats([1, 5, 2, 8, 3]) print(f"Min: {min_val}, Max: {max_val}") # Min: 1, Max: 8