Python Function with Return Value
Function with Return Value in Python
In Python, a function with a return value is a function that sends back a value to the caller using the return
statement. This allows the function to produce a result that can be used later in the program. Functions that return values are useful for encapsulating calculations or operations that need to be used repeatedly.
Defining a Function with Return Value
You can define a function that returns a value by including the return
statement in its body. The value specified in the return
statement is sent back to the point where the function was called.
Syntax
Example of a Function with Return Value
Here’s a simple example of a function that calculates the square of a number and returns the result:
Output:
Breakdown of the Example
Function Definition:
- The function
square
takes one parameter,number
. - The body of the function calculates the square of
number
usingnumber ** 2
and returns the result.
- The function
Function Call:
- The function is called with the argument
5
, and the result is stored in the variableresult
. - When
square(5)
is executed, it returns25
, which is printed to the console.
- The function is called with the argument
Using Return Values
The return value of a function can be used in various ways, such as:
- Storing it in a variable.
- Using it in expressions.
- Returning it as an argument to another function.
Example of Using Return Values
In this example, the multiply
function returns the product of 3
and 4
. The returned value is then added to 2
, resulting in 14
.
Returning Multiple Values
Python allows you to return multiple values from a function as a tuple. This can be useful when you want to return several related results.
Output:
In this example, the calculate_stats
function returns both the total and average of the list of numbers. The returned values are captured as a tuple, which can be accessed by indexing.
Summary
- A function with a return value uses the
return
statement to send a value back to the caller. - The returned value can be used in expressions, assigned to variables, or passed to other functions.
- You can return multiple values from a function, which are returned as a tuple and can be accessed using indexing.
Functions with return values are fundamental in Python programming, enabling you to create modular code that can perform computations and return results for further use.