In Python, functions can return values to the caller using the return statement. This allows functions to produce outputs based on their inputs, making them reusable and modular. This article explains the use of return values in Python with examples.
The return statement is used to send a value from a function to the caller. A function can return any data type, such as integers, strings, lists, or even other functions.
The following example demonstrates a function that returns the square of a number:
# Function to return the square of a number def square(num): return num * num # Calling the function and storing the result result = square(4) print("The square is:", result)
Output:
The square is: 16
A function in Python can return multiple values using tuples.
The following example demonstrates a function that returns the sum and product of two numbers:
# Function to return sum and product def calculate(num1, num2): return num1 + num2, num1 * num2 # Calling the function and unpacking the results sum_result, product_result = calculate(3, 5) print("The sum is:", sum_result) print("The product is:", product_result)
Output:
The sum is: 8 The product is: 15
Functions can also return complex data structures like lists and dictionaries.
# Function to return a list of squares def generate_squares(n): return [i * i for i in range(1, n + 1)] # Calling the function squares = generate_squares(5) print("Squares:", squares)
Output:
Squares: [1, 4, 9, 16, 25]
# Function to return a dictionary def user_details(name, age): return {"name": name, "age": age} # Calling the function details = user_details("Alice", 30) print("User details:", details)
Output:
User details: {'name': 'Alice', 'age': 30}
If a function does not include a return statement, or the return statement has no value, the function returns None.
# Function without a return statement def greet(name): print(f"Hello, {name}!") # Calling the function result = greet("Bob") print("Returned value:", result)
Output:
Hello, Bob! Returned value: None
Using the return statement, Python functions can provide outputs to their callers, enabling reusable and efficient code. Functions can return simple or complex data types, multiple values, or None. Experiment with these examples to understand how return values enhance the functionality of your programs.