Defining and Calling Functions

Here is a program that asks the user for a number and prints out its absolute value. Now suppose the program has to do that for TWO numbers. One way is to…

Why we want functions
Here is a program that asks the user for a number and prints out its absolute value. Now suppose the program has to do that for TWO numbers. One way is to copy the whole block a second time.
What a function is
One way to organize Python code and to make it more readable and reusable is to factor out useful pieces into reusable functions.
A function is a named group of programming instructions that accomplish a specific task. It may have parameters and return values. If we want to perform the task, we call the function by its name. A function may be called as many times as we wish to redo the task.
Defining a function
A function or procedure is a group of code that has a name and can be called using parentheses.
A function may have parameters or input variables. Parameters are input variables that provide information to the function to accomplish its task. Using parameters allows procedures to be generalized, enabling the procedures to be reused with a range of input values or arguments.
In Python, a function is defined using the def statement.
Factoring out the absolute value
Here is that redundant code converted into a function called absolute().
The block of code beginning with def is called the function definition. The function definition must precede any function calls.
Now we can reuse this code by calling absolute() with different inputs, as many times as we like.
What happens on each call
The first time absolute() is called, the input variable x has the value of -10. Once this function call is done executing, this value of x is released from memory.
The second time absolute() is called, a NEW variable x is created with the value 5. Once that call is done executing, this value of x is again released from memory.