Return statement
- Consits of the return keyword and an expression
- when the return stement executes, it exits the function
- to end a function
- send the result back to the caller
def f(p1,p2):
return expression
x = f(arg1, arg2)
- Send expression back to the caller.
Implied Return Statement
- Functions without return stament implicetly return a None it is the equivalent of returning a non-value. This makes it act like a procedure.
- Makes a function act like a procedure
- Examples include print(), sort() method
=> the difference between a function and procedures (in most cases functions provide more flexibility)
# procedure
def cube1(n):
print(n*n*n)
cube1(10)
# adding two cube results
cube1(2)+cube1(5)
# Output
# TypeError
n1 = cube1(2)
n2 = cube1(5)
print(n1)
# Output
None
You can avoid this with a function
# function
def cube2(n):
return n*n*n
# instead of printing an expression will return it by using return
n1 = cube2(2)
n2 = cube2(5)
n1+n2
# Output
# 133
# same result for
cube2(2) + cube2(5)
- use the procedure if you don’t need the return value.