Return statements (stuff like return True
) always terminate the execution of the function once they are reached. After the return statement, we return to the place in the program where the function was called, so that the part of the function that comes after a return statement that gets executed is not executed.
(Note: not every return statement is executed. For example, return statments might occur inside if statements, and are only executed conditionally. For example, if False: return 0 would never be executed)
def artsie_math(arg1, arg2, op):
'''Return arg1+arg2 depending on if command is "add" or "subtract". If
command is neither, print an error message.
Arguments:
arg1 -- a number
arg2 -- a number
command -- an operation (a str)
'''
if op == "add":
return arg1 + arg2
if op == "subtract":
return arg1 - arg2
#Will only be executed if command is neither "add" nor "subtract"
#because otherwise the function would have returned by this point.
print("I don't recognize this complicated mathematical operation")
if __name__ == '__main__':
print(artsie_math(2, 3, "add"))
Everything makes sense. We didn't print "I don't recognize this complicated mathematical operation"
becase the function returned arg1 + arg2
, which prevented later lines from being executed.
Now, let's try an uncrecognized operation
if __name__ == '__main__':
print(artsie_math(2, 3, "exponent"))
Now, the message did get printed, but an additional thing happenned: None
got printed. If a function doesn't return a value explicitly, the default return value will be None
. We actuall already so a function that doesn't return a value -- print
also returns None
a = artsie_math(2, 3, "exponent")
b = print("hi")
print(a, b)
It's nicer to first check the whether we need to do any computation, and then to do the computation if necessary. The following is equivalent to artsie_math
:
def artsie_math2(arg1, arg2, op):
'''Return arg1+arg2 depending on if command is "add" or "subtract". If
command is neither, print an error message.
Arguments:
arg1 -- a number
arg2 -- a number
op -- an operation (a str)
'''
if (op != "add") and (op != "subtract"):
print("I don't recognize this complicated mathematical operation")
return #We can do this. A return without a value means that we
#stop the execution of the function. (Note: in fact, we are
#returning a special object called None). So this is
#equivalent to
#return None
if op == "add":
return arg1 + arg2
elif op == "subtract":
return arg1 - arg2
#Would also work, because at this point we're sure the op is "subtract"
#else:
# return arg1 - arg2
#Would also work:
#return arg1 - arg2