Return Values of Functions in Python
Rama Krishna Vankam
15 Years of Experience: Train With a Java, Python, PHP Web Development Mastermind
?
### Return Values of Functions in Python
Here’s an example program with a clear explanation for the concept of "Return Values of Functions in Python" to be included in your course curriculum section on "Functions in Python":
?
### Program:
?
## Function that calculates the square of a number
def square(num):
return num * num
?
# Explanation:
In Python, the return statement is used to exit a function and send back a value (or values) to the point where the function was called. The value returned can then be used or stored for further operations. The return keyword is optional in Python. If a function doesn’t explicitly return a value, it will return None by default.
?
# Single Return Value:
The square() function demonstrates how a function returns a single value. The function takes an input num and returns its square using return num * num. In this case, the return value can be captured and stored in a variable (`result_square`), which is then used elsewhere in the program.
?
?
## Function that checks if a number is even or odd
def is_even(num):
if num % 2 == 0:
return True
else:
return False
?
# Explanation:
The is_even() function checks whether a number is even or odd using the modulus operator (`%`). If the number is even, it returns True; otherwise, it returns False. This demonstrates how a function can return different values based on conditional logic.
?
领英推荐
?
## Function that returns multiple values: sum and product of two numbers
def sum_and_product(a, b):
return a + b, a * b
?
# Explanation:
The sum_and_product() function returns two values: the sum and product of two numbers. In Python, a function can return multiple values separated by commas. When multiple values are returned, they are packed into a tuple. These values can be unpacked into separate variables when the function is called (as seen with result_sum, result_product = sum_and_product(3, 5)).
?
?
# Calling the functions and storing the return values
result_square = square(4) # Expected output: 16
result_is_even = is_even(7) # Expected output: False
result_sum, result_product = sum_and_product(3, 5) # Expected output: (8, 15)
?
# Printing the results
print(f"Square of 4: {result_square}")
print(f"Is 7 even?: {result_is_even}")
print(f"Sum of 3 and 5: {result_sum}, Product of 3 and 5: {result_product}")
?
# Output Explanation:
The program produces the following output when executed:
Square of 4: 16
Is 7 even?: False
Sum of 3 and 5: 8, Product of 3 and 5: 15
?
This section explains how the return statement works in Python, and demonstrates how to return a single value, conditional values, and multiple values from a function.
15 Years of Experience: Train With a Java, Python, PHP Web Development Mastermind
1 个月