Various Function Return Methods
Functions are classified into the following 3 types based on their return
method.
Exiting a Function Without Returning a Result
When a function is called without the return
keyword, it returns None
.
This is used when a function simply outputs a value using print
but does not explicitly return a value.
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 flow of the code returns to the calling location along with the returned 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.