Functions: Return Value
Welcome to the lesson on functions. Now, we'll proceed by discussing return statements and how they allow functions to send back results to the caller.
` ˙⋆˖⁺‧₊☽◯☾₊‧⁺˖⋆˙ `
Return Statements
The return statement is used in a function to send a value back to the caller. This allows functions to produce a result that can be stored in a variable, used in expressions, or passed to other functions.
Using Return Statements
To use a return statement, you simply include the return keyword followed by the value or expression you want to return. When the return statement is executed, the function terminates and the specified value is returned to the caller.
#Example: Function with a return statement
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
In this example, the add( ) function takes two parameters, a and b, and returns their sum. The result of the function call add(5, 3) is stored in the variable result and then printed.
Returning Multiple Values
In Python, a function can return multiple values as a tuple. This allows you to return several pieces of information from a single function call.
#Example: Function returning multiple values
def get_name_age():
name = "Albus"
age = 115
return name, age
name, age = get_name_age()
print(name) # Output: Albus
print(age) # Output: 115
In this example, the get_name_age( ) function returns both a name and an age. The returned values are unpacked into the variables name and age.
Using Return Values in Expressions
Return values from functions can be used in expressions or passed to other functions, making your code more modular and reusable.
#Example: Using return values in expressions
def square(x):
return x * x
square_4 = square(4)
sum_squares = square(3) + square(4)
print(square_4) # Output: 16
print(sum_squares) # Output: 25
In this example, the square( ) function returns the square of its parameter. The return values are used in further calculations and expressions.
Practical Application
In the Inner Sanctum, you will learn to create advanced spells (functions) that accept parameters and return values.
⋆˖⁺‧₊ Create a function named calculate_final_power that takes two parameters: base_power (float) and multiplier (float). This function should return the product of these parameters. ₊‧⁺˖⋆
⋆˖⁺‧₊ Call this function with base_power as 100 and multiplier as 1.5, storing the result in a variable and displaying it using the print() spell. ₊‧⁺˖⋆
Sample Output:
Final Power: 150.0
Prove your mastery by creating and invoking spells with parameters and return values.