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."
# 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.
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