Python en:Functions

Introduction
Functions are reusable pieces of programs. They allow you to give a name to a block of statements and you can run that block using that name anywhere in your program and any number of times. This is known as calling the function. We have already used many built-in functions such as the len and range.

The function concept is probably the most important building block of any non-trivial software (in any programming language), so we will explore various aspects of functions in this chapter.

Functions are defined using the def keyword. This is followed by an identifier name for the function followed by a pair of parentheses which may enclose some names of variables and the line ends with a colon. Next follows the block of statements that are part of this function. An example will show that this is actually very simple:

Example:

Output:

$ python function1.py   Hello World! Hello World!

How It Works:

We define a function called sayHello using the syntax as explained above. This function takes no parameters and hence there are no variables declared in the parentheses. Parameters to functions are just input to the function so that we can pass in different values to it and get back corresponding results.

Notice that we can call the same function twice which means we do not have to write the same code again.

Function Parameters
A function can take parameters, which are values you supply to the function so that the function can do something utilising those values. These parameters are just like variables except that the values of these variables are defined when we call the function and are already assigned values when the function runs.

Parameters are specified within the pair of parentheses in the function definition, separated by commas. When we call the function, we supply the values in the same way. Note the terminology used - the names given in the function definition are called parameters whereas the values you supply in the function call are called arguments.

Example:

Output:

$ python func_param.py   4 is maximum 7 is maximum

How It Works:

Here, we define a function called printMax where we take two parameters called a and b. We find out the greater number using a simple if..else statement and then print the bigger number.

In the first usage of printMax</tt>, we directly supply the numbers i.e. arguments. In the second usage, we call the function using variables. printMax(x, y)</tt> causes value of argument x</tt> to be assigned to parameter a</tt> and the value of argument y</tt> assigned to parameter b</tt>. The printMax function works the same in both the cases.

Local Variables
When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function i.e. variable names are local to the function. This is called the scope of the variable. All variables have the scope of the block they are declared in starting from the point of definition of the name.

Example:

Output:

$ python func_local.py   x is 50 Changed local x to 2 x is still 50

How It Works:

In the function, the first time that we use the value of the name x</tt>, Python uses the value of the parameter declared in the function.

Next, we assign the value 2</tt> to x</tt>. The name x</tt> is local to our function. So, when we change the value of x</tt> in the function, the x</tt> defined in the main block remains unaffected.

In the last print</tt> function call, we display the value of x</tt> in the main block and confirm that it is actually unaffected.

Using The global Statement
If you want to assign a value to a name defined at the top level of the program (i.e. not inside any kind of scope such as functions or classes), then you have to tell Python that the name is not local, but it is global. We do this using the global</tt> statement. It is impossible to assign a value to a variable defined outside a function without the global</tt> statement.

You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). However, this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable's definition is. Using the <tt>global</tt> statement makes it amply clear that the variable is defined in an outermost block.

Example:

Output:

$ python func_global.py   x is 50 Changed global x to 2 Value of x is 2

How It Works:

The <tt>global</tt> statement is used to declare that <tt>x</tt> is a global variable - hence, when we assign a value to <tt>x</tt> inside the function, that change is reflected when we use the value of <tt>x</tt> in the main block.

You can specify more than one global variable using the same <tt>global</tt> statement. For example, <tt>global x, y, z</tt>.

Using nonlocal statement
We have seen how to access variables in the local and global scope above. There is another kind of scope called "nonlocal" scope which is in-between these two types of scopes. Nonlocal scopes are observed when you define functions inside functions.

Since everything in Python is just executable code, you can define functions anywhere.

Let's take an example:

Output:

$ python func_nonlocal.py   x is 2 Changed local x to 5

How It Works:

When we are inside <tt>func_inner</tt>, the 'x' defined in the first line of <tt>func_outer</tt> is relatively neither in local scope nor in global scope. We declare that we are using this x by <tt>nonlocal x</tt> and hence we get access to that variable.

Try changing the <tt>nonlocal x</tt> to <tt>global x</tt> and also by removing the statement itself and observe the difference in behavior in these two cases.

Default Argument Values
For some functions, you may want to make some of its parameters as optional and use default values if the user does not want to provide values for such parameters. This is done with the help of default argument values. You can specify default argument values for parameters by following the parameter name in the function definition with the assignment operator (<tt>=</tt>) followed by the default value.

Note that the default argument value should be a constant. More precisely, the default argument value should be immutable - this is explained in detail in later chapters. For now, just remember this.

Example:

Output:

$ python func_default.py   Hello WorldWorldWorldWorldWorld

How It Works:

The function named <tt>say</tt> is used to print a string as many times as specified. If we don't supply a value, then by default, the string is printed just once. We achieve this by specifying a default argument value of <tt>1</tt> to the parameter <tt>times</tt>.

In the first usage of <tt>say</tt>, we supply only the string and it prints the string once. In the second usage of <tt>say</tt>, we supply both the string and an argument <tt>5</tt> stating that we want to say the string message 5 times.


 * Important
 * Only those parameters which are at the end of the parameter list can be given default argument values i.e. you cannot have a parameter with a default argument value before a parameter without a default argument value in the order of parameters declared in the function parameter list.
 * This is because the values are assigned to the parameters by position. For example, <tt>def func(a, b=5)</tt> is valid, but <tt>def func(a=5, b)</tt> is not valid.

Keyword Arguments
If you have some functions with many parameters and you want to specify only some of them, then you can give values for such parameters by naming them - this is called keyword arguments - we use the name (keyword) instead of the position (which we have been using all along) to specify the arguments to the function.

There are two advantages - one, using the function is easier since we do not need to worry about the order of the arguments. Two, we can give values to only those parameters which we want, provided that the other parameters have default argument values.

Example:

Output:

$ python func_key.py   a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50

How It Works:

The function named <tt>func</tt> has one parameter without default argument values, followed by two parameters with default argument values.

In the first usage, <tt>func(3, 7)</tt>, the parameter <tt>a</tt> gets the value <tt>3</tt>, the parameter <tt>b</tt> gets the value <tt>7</tt> and <tt>c</tt> gets the default value of <tt>10</tt>.

In the second usage <tt>func(25, c=24)</tt>, the variable <tt>a</tt> gets the value of 25 due to the position of the argument. Then, the parameter <tt>c</tt> gets the value of <tt>24</tt> due to naming i.e. keyword arguments. The variable <tt>b</tt> gets the default value of <tt>5</tt>.

In the third usage <tt>func(c=50, a=100)</tt>, we use keyword arguments completely to specify the values. Notice, that we are specifying value for parameter <tt>c</tt> before that for <tt>a</tt> even though <tt>a</tt> is defined before <tt>c</tt> in the function definition.

VarArgs parameters

 * TODO
 * Should I write about this in a later chapter since we haven't talked about lists and dictionaries yet?

Sometimes you might want to define a function that can take any number of parameters, this can be achieved by using the stars:

Output:

$ python total.py   166

How It Works:

When we declare a starred parameter such as <tt>*param</tt>, then all the positional arguments from that point till the end are collected as a list called 'param'.

Similarly, when we declare a double-starred parameter such as <tt>**param</tt>, then all the keyword arguments from that point till the end are collected as a dictionary called 'param'.

We will explore lists and dictionaries in a later chapter.

Keyword-only Parameters
If we want to specify certain keyword parameters to be available as keyword-only and not as positional arguments, they can be declared after a starred parameter:

Output:

$ python keyword_only.py   66 Traceback (most recent call last): File "test.py", line 12, in    print(total(10, 1, 2, 3)) TypeError: total needs keyword-only argument vegetables

How It Works:

Declaring parameters after a starred parameter results in keyword-only arguments. If these arguments are not supplied a default value, then calls to the function will raise an error if the keyword argument is not supplied, as seen above.

If you want to have keyword-only arguments but have no need for a starred parameter, then simply use an empty star without using any name such as <tt>def total(initial=5, *, vegetables)</tt>.

The return Statement
The <tt>return</tt> statement is used to return from a function i.e. break out of the function. We can optionally return a value from the function as well.

Example:

Output:

$ python func_return.py   3

How It Works:

The <tt>maximum</tt> function returns the maximum of the parameters, in this case the numbers supplied to the function. It uses a simple <tt>if..else</tt> statement to find the greater value and then returns that value.

Note that a <tt>return</tt> statement without a value is equivalent to <tt>return None</tt>. <tt>None</tt> is a special type in Python that represents nothingness. For example, it is used to indicate that a variable has no value if it has a value of <tt>None</tt>.

Every function implicitly contains a <tt>return None</tt> statement at the end unless you have written your own <tt>return</tt> statement. You can see this by running <tt>print(someFunction)</tt> where the function <tt>someFunction</tt> does not use the <tt>return</tt> statement such as:

The <tt>pass</tt> statement is used in Python to indicate an empty block of statements.


 * Note
 * There is a built-in function called <tt>max</tt> that already implements the 'find maximum' functionality, so use this built-in function whenever possible.

DocStrings
Python has a nifty feature called documentation strings, usually referred to by its shorter name docstrings. DocStrings are an important tool that you should make use of since it helps to document the program better and makes it easier to understand. Amazingly, we can even get the docstring back from, say a function, when the program is actually running!

Example:

Output:

$ python func_doc.py   5 is maximum Prints the maximum of two numbers. The two values must be integers.

How It Works:

A string on the first logical line of a function is the docstring for that function. Note that DocStrings also apply to modules and classes which we will learn about in the respective chapters.

The convention followed for a docstring is a multi-line string where the first line starts with a capital letter and ends with a dot. Then the second line is blank followed by any detailed explanation starting from the third line. You are strongly advised to follow this convention for all your docstrings for all your non-trivial functions.

We can access the docstring of the <tt>printMax</tt> function using the <tt>__doc__</tt> (notice the double underscores) attribute (name belonging to) of the function. Just remember that Python treats everything as an object and this includes functions. We'll learn more about objects in the chapter on classes.

If you have used <tt>help</tt> in Python, then you have already seen the usage of docstrings! What it does is just fetch the <tt>__doc__</tt> attribute of that function and displays it in a neat manner for you. You can try it out on the function above - just include <tt>help(printMax)</tt> in your program. Remember to press the <tt>q</tt> key to exit <tt>help</tt>.

Automated tools can retrieve the documentation from your program in this manner. Therefore, I strongly recommend that you use docstrings for any non-trivial function that you write. The <tt>pydoc</tt> command that comes with your Python distribution works similarly to <tt>help</tt> using docstrings.

Annotations
Functions have another advanced feature called annotations which are a nifty way of attaching additional information for each of the parameters as well as the return value. Since the Python language itself does not interpret these annotations in any way (that functionality is left to third-party libraries to interpret in any way they want), we will skip this feature in our discussion. If you are interested to read about annotations, please see the Python Enhancement Proposal No. 3107.

Summary
We have seen so many aspects of functions but note that we still haven't covered all aspects of them. However, we have already covered most of what you'll use regarding Python functions on an everyday basis.

Next, we will see how to use as well as create Python modules.

Previous Next