Functions are self-contained programs that perform a specific task. They can be incorporated into larger programs. Then you can use them at any time, in any place. This saves you the time and effort of having to retell the computer what to do every time it does a common task.
There are two types of functions: the ones that you write yourself and include in your code, and the ones that are included in Python natively, which carry out common procedures, such as converting an integer to a string, or finding the length of a string. The latter function from the "math" module were considered in Sect. Arithmetic
We’re going to look at writing a simple function now, and demonstrate how it can be useful in the real world code. Let's make a simple function which adds a to numbers and returns a message message with the sum:
To define the function, we need to use the def keyword, and then the name of the function. Next, we type two parentheses to specify arguments (a way of passing data into a function when we don’t know which variable or variables that data is going to be) and then a colon. After that, all of the code that we want to be encased within the function should be indented.
It is important to make a documentation line for your functions. This can be doe directly after the statement def:
You can also use default values for the arguments:In the last call we did not specify the family name, do the default family name was "Smith" The nice thing about Python is that it does not care about data types when we call this function:
All parameters in Python are passed to functions by reference: if one changes what a parameter refers to within a function, the change also reflects back in the calling function.
Let us consider an example:I this example we print the result of this function and the type of the output variable.
Now change changeme("A","B") by changeme(1,2). What do you see? This example illustrates that the the type can be any, as long as operators in the function support the input variables:
One can specify a default parameter to a function. You can just use the assignment operator "=" when you define a function:
It is also useful to use "None".