Calling Functions

When you want to use a function definition you have to call the function. The way that you call a function in Python looks like this:

name(arguments)

The name of the function always comes before a set of parentheses. These parentheses contain the values that are passed into the function in order for it to work; we call the set of values that are placed inside the parentheses when calling a function “arguments”.

Returning a Result to a Function’s Caller:
When a function finishes executing, it returns control to its caller —- that is, the line of code that called the function. In the example above, the return statement: return number ** 2 first squares number, then terminates the function and gives the result back to the caller. In this example, the first caller is square(7), so 49 is returned to this statement. Think of the return value, 49, as simply replacing the call square(7). Function calls can also be embedded in expressions. The following code calls square first, then print displays the result:

print('The square of 7 is ', square(7))

Here, too, think of the return value, 49, as simply replacing the call square(7), which would indeed produce the output shown above. There are two other ways to return control from a function to its caller:

  • Executing a return statement without an expression terminates the function and implicitly returns the value None to the caller.

  • The Python documentation states that None represents the absence of a value. None evaluates to False in conditions: When there’s no return statement in a function, it implicitly returns the value None after executing the last statement in the function’s block.

What Happens When You Call a Function:
The expression square(7) passes the argument 7 to square’s parameter number. Then square calculates number ** 2 and returns the result. The parameter number exists only during the function call. It’s created on each call to the function to receive the argument value, and it’s destroyed when the function returns its result to the caller. A function’s parameters and variables defined in its block are all local variables; they can be used only inside the function and exist only while the function is executing. Trying to access a local variable outside its function’s block causes a NameError, indicating that the variable is not defined.