Python Functions
FUNCTIONS
Definition
A function is a group of related statements that performs a specific task. Functions help break our
program into smaller and modular chunks. As our program grows larger and larger, functions make it
more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
Functions that readily come with Python are called built-in functions
e.g. prin(), input(), len(), enumerate()
2. User-defined functions - Functions defined by the users themselves.
Functions that we define ourselves to do certain specific task are referred as user-defined
functions.
Advantages of user-defined functions
User-defined functions help to decompose a large program into small segments
which makes program easy to understand, maintain and debug.
If repeated code occurs in a program. Function can be used to include those codes
and execute when needed by calling that function.
Programmers working on large project can divide the workload by making different
functions.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition that consists of the following components.
1. Keyword def that marks the start of the function header.
2. A function name to uniquely identify the function. Function naming follows the same rules
of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must
have the same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Example of a function
How to call a function?
Once we have defined a function, we can call it from another function, program, or even the Python
prompt. To call a function we simply type the function name with appropriate parameters.
Docstrings
The first string after the function header is called the docstring and is short for documentation
string. It is briefly used to explain what a function does.
Although optional, documentation is a good programming practice. Unless you can remember what
you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We generally
use triple quotes so that docstring can extend up to multiple lines. This string is available to us as the
__doc__ attribute of the function.
For example:
Try running the following into the Python shell to see the output.
The return statement
The return statement is used to exit a function and go back to the place from where it was called.
Syntax of return
return [expression_list]
This statement can contain an expression that gets evaluated and the value is returned. If there is no
expression in the statement or the return statement itself is not present inside a function, then the
function will return the None object.
Example of return
Scope and Lifetime of variables
Scope of a variable is the portion of a program where the variable is recognized. Parameters and
variables defined inside a function are not visible from outside the function. Hence, they have a local
scope.
The lifetime of a variable is the period throughout which the variable exists in the memory. The
lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
Here is an example to illustrate the scope of a variable inside a function.
Here, we can see that the value of x is 20 initially. Even though the function my_func() changed the
value of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function) from the one
outside. Although they have the same names, they are two different variables with different scopes.
On the other hand, variables outside of the function are visible from inside. They have a global
scope.
We can read these values from inside the function but cannot change (write) them. In order to
modify the value of variables outside the function, they must be declared as global variables using
the keyword global.
Python Function Arguments
An argument is the value sent to the function when it is called in Python.
There are 3 types of arguments that we are going to discuss
Python Default Arguments
Function arguments can have default values in Python.
We can provide a default value to an argument by using the assignment operator (=). Here is an
example.
In this function, the parameter name does not have a default value and is required (mandatory)
during a call.
On the other hand, the parameter msg has a default value of "Good morning!". So, it is optional
during a call. If a value is provided, it will overwrite the default value.
Any number of arguments in a function can have a default value. But once we have a default
argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example, if we had
defined the function header above as:
def greet(msg = "Good morning!", name):
We would get an error as:
SyntaxError: non-default argument follows default argument
Python Keyword Arguments
When we call a function with some values, these values get assigned to the arguments according to
their position.
For example, in the above function greet(), when we called it as greet("Bruce", "How do you do?"),
the value "Bruce" gets assigned to the argument name and similarly "How do you do?" to msg.
Python allows functions to be called using keyword arguments. When we call functions in this way,
the order (position) of the arguments can be changed. Following calls to the above function are all
valid and produce the same result.
As you can see, we can mix positional arguments with keyword arguments during a function call. But
we must keep in mind that keyword arguments must follow positional arguments.
Having a positional argument after keyword arguments will result in errors. For example, the
function call as follows:
greet(name="Bruce","How do you do?")
Will result in an error:
SyntaxError: non-keyword arg after keyword arg
Python Arbitrary Arguments
Sometimes, we do not know in advance the number of arguments that will be passed into a
function. Python allows us to handle this kind of situation through function calls with an arbitrary
number of arguments.
In the function definition, we use an asterisk (*) before the parameter name to denote this kind of
argument. Here is an example.
Here, we have called the function with multiple arguments. These arguments get wrapped up into a
tuple before being passed into the function. Inside the function, we use a for loop to retrieve all the
arguments back.
Python Global, Local and Nonlocal variables
Global Variables
In Python, a variable declared outside of the function or in global scope is known as a global variable.
This means that a global variable can be accessed inside or outside of the function.
Let's see an example of how a global variable is created in Python.
Example 1: Create a Global Variable
In the above code, we created x as a global variable and defined a foo() to print the global variable x.
Finally, we call the foo() which will print the value of x.
What if you want to change the value of x inside a function?
The output shows an error because Python treats x as a local variable and x is also not defined inside
foo().
To make this work, we use the global keyword. Visit Python Global Keyword to learn more.
Local Variables
A variable declared inside the function's body or in the local scope is known as a local variable.
Example 2: Accessing local variable outside the scope
The output shows an error because we are trying to access a local variable y in a global scope
whereas the local variable only works inside foo() or local scope.
Let's see an example on how a local variable is created in Python.
Example 3: Create a Local Variable
Normally, we declare a variable inside the function to create a local variable.
Global and local variables
We will show how to use global variables and local variables in the same code.
Example 4: Using Global and Local variables in the same code
In the above code, we declare x as a global and y as a local variable in the foo(). Then, we use
multiplication operator * to modify the global variable x and we print both x and y.
After calling the foo(), the value of x becomes global global because we used the x * 2 to print two
times global. After that, we print the value of local variable y i.e local.
Example 5: Global variable and Local variable with same name
In the above code, we used the same name x for both global variable and local variable. We get a
different result when we print the same variable because the variable is declared in both scopes, i.e.
the local scope inside foo() and global scope outside foo().
When we print the variable inside foo() it outputs local x: 10. This is called the local scope of the
variable.
Similarly, when we print the variable outside the foo(), it outputs global x: 5. This is called the global
scope of the variable.
Nonlocal Variables
Nonlocal variables are used in nested functions whose local scope is not defined. This means that
the variable can be neither in the local nor the global scope.
Let's see an example of how a nonlocal variable is used in Python.
We use nonlocal keywords to create nonlocal variables.
Example 6: Create a nonlocal variable
In the above code, there is a nested inner() function. We use nonlocal keywords to create a nonlocal
variable. The inner() function is defined in the scope of another function outer().
Note : If we change the value of a nonlocal variable, the changes appear in the local variable.
Global keyword
Gglobal keyword allows you to modify the variable outside of the current scope. It is used to create a
global variable and make changes to the variable in a local context.
Rules of global Keyword
The basic rules for global keyword in Python are:
When we create a variable inside a function, it is local by default.
When we define a variable outside of a function, it is global by default. You don't have to use
global keyword.
We use global keyword to read and write a global variable inside a function.
Use of global keyword outside a function has no effect.
Use of global Keyword
Let's take an example.
Example 1: Accessing global Variable From Inside a Function
When we run the above program, the output will be: 1
However, we may have some scenarios where we need to modify the global variable from inside a
function.
Example 2: Modifying Global Variable from Inside the Function
When we run the above program, the output shows an error:
UnboundLocalError: local variable 'c' referenced before assignment
This is because we can only access the global variable but cannot modify it from inside the function.
The solution for this is to use the global keyword.
Example 3: Changing Global Variable From Inside a Function using global
In the above program, we define c as a global keyword inside the add() function.
Then, we increment the variable c by 2, i.e c = c + 2. After that, we call the add() function. Finally, we
print the global variable c.
As we can see, change also occurred on the global variable outside the function, c = 2.