Various Function Return Methods
Functions can be categorized into three types based on how they use the return
keyword.
Exiting a Function Without Returning a Result
When a function is called without the return
keyword, it returns None
.
This applies when a function uses print
to display a result but does not explicitly return anything."
Example of a Function Without a Return
# Function to print a message
def print_message(message):
# Ends without return resulting in None
print(message)
result = print_message("Hello")
# Prints None
print(result)
Returning a Value and Returning to the Call Location
When a value is specified after the return
keyword, that value is returned.
The code then returns to the calling location with the specified result.
Example of a Function Returning a Value
def add(x, y):
# Returns calculation result to the call location of add function
return x + y
# 3 + 5 = 8
result = add(3, 5)
print(result)
Exiting a Function Without Returning a Value
Using only the return
keyword, a function stops execution and returns None
.
This method is useful when you want to immediately terminate the function execution under specific conditions.
Exiting Function When num is Negative
def check_number(num):
if num < 0:
return
print("It is a positive number.")
result1 = check_number(-1)
print(result1) # None
result2 = check_number(1)
print(result2) # It is a positive number.
In the example above, when num
is negative, the function is immediately terminated using only the return
keyword, resulting in None
.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.