Printing the Sum of Two Numbers
In the following example, the function calculates the sum of its arguments and prints the result. Notice that even though the function uses a return keyword in other contexts, here it simply performs an action by printing the sum directly to the console.Exiting a Function Early
Sometimes, you might want to exit a function before it completes all its statements based on a certain condition. For example, if the computed sum equals 0, we may wish to exit the function immediately without printing anything.If the condition for early exit is met, the function stops executing, and any code after the return statement will not run.
Implicit Return Value: None
The return keyword not only controls the execution flow but also specifies the value that a function call will evaluate to. If no return statement is explicitly provided in a function, Python returns a default value, None. The next example defines a function that returns True when the provided argument is an even number. If the input is not even, the function ends without an explicit return, so it returns None by default.Summary
The return keyword is a versatile tool in Python that:- Stops the execution of a function when encountered.
- Can be used to exit a function early based on a condition.
- Returns a value to the caller, or defaults to None if no value is explicitly specified.