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.
# 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.
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.
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
.
What does a Python function return if the return
keyword is not used?
0
An empty string
None
The function itself
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result