Python Function

 

In this section we will learn about the function in Python, their syntax and use and how they are defined and the types of functions in Python programming language.

 

Definition of a function

A function in Python is a group or block of statements that are defined by the user to perform a specific task. The main advantage of function is that they can reduce the length of the actual program by breaking the program into smaller modules. Functions make the program readable and easy to modify.

 

Syntax of function in python

The following is the syntax to define a function in Python programming language:

def name of function (parameters or arguments):

         “””docstring”””

statement(s)

In the above syntax, the keyword def is used to declare that a function is used. The keyword def is used to define the header of the function in Python.

Next is the name of function which assigns a unique name to the function. The rules for writing names of functions are given below:

  1. The name of a function can contain letters both upper case and lowercase from (a-z) or (A-Z). A function name can also contain underscore (_). Underscore is used to clarify the name of the function for example my_file is clearer than myfile.
  2. We cannot start the name of a function from a digit or number for example 3file is invalid but file3 is valid.
  3. We cannot use the keywords as the names of functions. Consider the following example to demonstrate this:
  4. Special symbols cannot be used as the name or between the names of functions such as &, #, $, %, etc.
  5. Function name can be of any length.
  6. Blank spaces are not allowed in the name of a function.

 

Key points to remember

  1. Python is a case sensitive programming language and functions with same name but the difference of upper case and lower case letters are not the same for example x and X are different.
  2. The names of functions should be meaningful that when a user looks back the code after a long time he should be able to understand that what this function is for? For example a counter variable of a loop is recommended to be named as count instead of c etc.
  3. In a function name if there are more than one word then they should be separated by an underscore (_).
  4. To make a function name more meaningful the user should capitalize each word in variable name. This is concept is known as camel case style. For example the variable should be named as GeneratorExample instead of generator example.

In the syntax of the definition of the function parameters are the arguments that should be passed as a value to the function to perform a specific task. The parameters of the function are optional that is it is not mandatory to pass parameters to a function.

The colon at the end of the first line indicates that the function definition is being done and it has been declared. This demonstrates that the function header is declared.

The doc string inside the body of the function is completely option. The doc string is only used to include a string that will describe the functionality of the function that is what is going on in the function.

Now move in to the body of the function that has a number of statements. The block of statements describes the functionality of the function. That this specific function performs a specific task.

In the function definition we can also return a value, to return a value is optional.

 

EXAMPLE of a function in Python

CODE

def addition(int a, int b):

        print(“This function prints the sum of numbers”)

OUTPUT

This function prints the sum of numbers

In the above example a function is being defined and its name is addition(), the above function adds two numbers that are passed as an argument or parameters. The values of the two numbers can be entered by the user. In the body of the function there is a print statement that prints the message that this function prints the sum of numbers.

The indentation of the block of statements is usually 4 spaces and the statements that are not indented will not be referred to as the body of the function.

 

Function Call in Python

In Python a defined function can be called from another defined function or the program. A function in Python programming language can be called by simply writing the name of the functions with the parameters enclosed in parentheses.

Consider the following example in which a function is being defined and later it is called through its name by passing the parameters of the function:

 

EXAMPLE of calling function in Python

CODE

def addition(int a, int b):

        “””This function adds two numbers”””

        print(“This function prints the sum of numbers”)

addition(4, 6)

In the above lines of code a function is defined with a name addition and two parameters are passed. Later outside the body of function the function is called by its name and two values are passed to perform the specified function that is addition of two numbers.

 

DOCSTRING

Inside the body of function the first statement contains a string which is used to for the documentation of the function that is to define the functionality of the function. The string simply defines the function in a line and the user gets the overview of the function.

For programmers it is a good practice to document the program this makes the modification of the program more efficient and convenient. For future use to document a program is a good practice.

In the above example, the function has a doc string right after the header of the function. It can be seen that triple quotes are used to define the doc string. The triple quotes are used so that the doc string can be extended to multiple lines. The doc string has no effect on the program and the interpreter ignores it, this is only to increase the readability of the program.

Consider the following example in which a doc string is declared right after the header of the function.

CODE

def addition(int a, int b):

        “””This function adds two numbers”””

        print(“This function prints the sum of numbers”)

addition(4, 6)

There will be no effect on the output of the program. And the function will calculate only the sum of the two numbers and will display the message that this function prints the sum of numbers.

 

The Return Statement

The return statement is used to return the value that is obtained after evaluation or after performing a specific task. The return statement is optional in the function of Python. In Python the return statement can also be used to exit from a function and to transfer the control from where the function was called.\

The following is the syntax of the return statement if a function:

 

SYNTAX of return statement in a function

return [expression]

In the return statement we can also evaluate expressions to a value and then return that values. As the return statement is optional in the function therefore, if a return statement is without any return value or expression then none will be returned. In Python none is equivalent to 0.

Consider the following example in which a return statement is used that do not return any value and hence it returns none.

EXAMPLE

CODE

def addition(int a, int b):

        “””This function adds two numbers”””

        print(“This function prints the sum of numbers”)

        return

OUTPUT

None

 

EXAMPLE of return statement

Consider the following example in which a function is defined and it returns a value:

CODE

>>> def add(a, b):

          c = a + b

          return c

>>> print(“The sum of a and b is”)

>>> print(add(4, 5))

OUTPUT

The sum of a and b is

9

9

In the above example, a function is defined with a name add that has two arguments. In the function the value after addition of a and b is stored in the variable c and in the next line c is returned. Outside the body of the function first print statement is used to simply print a statement and in the next print statement we called the function by passing the values of the parameters, the function returns the value in the print statement and the value is printed.

 

Working of functions in Python

Consider the following pictorial representation of the working of a function in Python:

def function name():
arrorsBlock of statements

function name ();           arror

Block of statements outside function

In the above example, the first step is to define the function with its header. In the definition of the function there are statements that perform the specific task for which the function was defined. Outside the definition of the function there is calling of function. A function is called by using its name and then a semi colon after the name of the function.

When a function is called the control is transferred to the body of the corresponding function. After the execution of the statements in the function the control is returned back outside the function after function calling. If the function returns a value then the value will be returned at function calling.

 

Scope and lifetime of variables

By scope of variables we mean the part of the program or code in which a variable can be accessed. A variable declared inside a function is visible to that function only. This variable cannot be accessed outside the function and hence this variable is called local variable. The local variable has a local scope.

By life time of a variable we mean the time period throughout which a variable exists in the memory. Hence the lifetime of a local variable is as long as the function executes. The variables are destroyed when the control is transferred to the statements outside the body of the function.

Because of this the value of the variable is not recognized when the control is transferred outside the function. Consider the following example in which the scope and life time of the local variable is demonstrated using function:

EXAMPLE

CODE

>>> def add(a, b):

          c = a+b

          return c

>>> print(“The sum of a and b is”)

>>> print(add(4, 5))

OUTPUT

The sum of a and b is

9

the-sum-of-a-and-b-is

In the above example, a function is defined with a name add that has two arguments. In the function the value after addition of a and b is stored in the variable c and in the next line c is returned. Outside the body of the function first print statement is used to simply print a statement and in the next print statement we called the function by passing the values of the parameters, the function returns the value in the print statement and the value is printed.

In the function a variable c is storing the result. This variable has a local scope and is known to only the function in which it is declared that is add(a, b). The variables a and b are also local variables because they are known to only the function in which they are declared. When the control is transferred outside the function the variables are destroyed.

Consider the following example in which we have declared two variables one inside the function and the other outside the function with the same, in the following example the scope of variables x (inside the function) and x (outside the function) has been illustrated:

CODE

>>> def example():

          x = 4

          print(“The values of x inside the function:”,x)

>>> x = 6

>>> example()

>>> print(“The values of x outside the function:”,x)

OUTPUT

The values of x inside the function: 4

The values of x outside the function: 6

the-values-of-x-outside-the-function

In the above example, x is once declared inside the function and is assigned a value 4. The value of x is then printed using the print statement. Outside the function x is declared and assigned a value 6. Then the function is called the value of x is printed inside the function is 4 and value of x outside the function is printed is 6.

The variables that are declared outside the functions have a global scope and they are visible inside the function. These variables can be accessed and read inside the function but cannot be changed.

 

Types of functions

Functions in any programming language can be divided into two parts, following are the parts in which a function is divided:

  1. Built in functions
  2. User defined functions

 

Python Programming built in functions

In python there are a number of functions that are already defined in the language. These functions can be used anytime and anywhere in the program or code. These functions are known as built in functions. A function can be defined as the number of statements that are used to perform certain task. The built in functions are built in the interpreter of Python.

The most commonly used functions in Python are print () used to print something on the screen, input () used to input any data from the user, etc. In Python 3, there are approximately 68 built in functions. Consider the following table in which the built in functions are described:

Functions Usage
abs () It is used to return the absolute value for a number.
all () It is used to return a True if all the iterables are True.
any () It is used to return a True if any of the iterables is True.
ascii () It is used to return a string that has printable objects.
bin () It is used to convert an integer to binary digit.
bool () It is used to convert a value to Boolean.
bytearray () It is used to return a new array of bytes.
bytes () It is used to return an object in bytes.
callable () This function returns a True if argument seems callable otherwise it returns false.
chr () It returns a string that represents a character.
classmethod () It returns a class method for a function.
compile () It compiles the source into code.
complex () It is used to convert a number to complex number or create a complex number.
delattr () It is used to delete the attribute of an object.
dict () It is used to create a new dictionary.
dir () It is used to return the names in list.
divmode () It used to return quotient and remainder after division of numbers.
enumerate () It returns an enumerate object.
eval () It evaluates an argument as a Python expression.
exec () It dynamically executes the Python code.
filter () It filters the iterator for which function has returned True.
float () It is used to convert a string or integer to floating point number.
format () It is used to format a value.
frozenset () It is used to return a new frozenset object.
getattr () It is used to get the attribute of an object.
globals () It is used to return a dictionary that has current global symbol table.
hasattr () It returns a true if name is one of the object’s attributes.
hash () It is used to return a hash value of an object.
help () It is used for built in help system.
hex () It is used to convert an integer to hexadecimal.
id () It is used to return the identity of an object.
input () It takes input from the user.
int() It converts a number or string or floating point number to integer data type.
isinstance () It returns True if the argument is instance.
issubclass () It returns True if a class is subclass.
iter () It is used to return an iterator object.
len () It is used to return the length of an object.
list () It is used to return a list.
locals () It is used to return a dictionary that has current local symbol table.
map () It is used to return an iterator which applies function to every item of iterable.
max () It is used to return the largest number.
memoryview () It is used to return a memory view.
min () It is used to return the smallest number.
next () It is used to retrieve the next item.
object () It is used to return a new object.
oct ()  It is used to convert an integer to octal string.
open () It is used to open a file.
ord () It is used to return integer that has Unicode.
pow () It returns a value resulted in power raise to a number.
print () It is used for printing on output screen.
property () It is sed to return the property of an attribute.
range () It is used in loops usually to represent iterations.
repr () It is used to represent a string.
reversed () It is used to reverse iteration.
round () It is used to round off a floating point number.
set () It returns a new set object.
setattr () It is used to assign a value to an attribute.
slice () It is sued to return a slice object.
sorted () It is used to return a sorted list.
staticmethod () It returns a static method for a function.
str () It returns an object in str version.
sum () It is used to sum items.
super () It is used to return objects that delegates method calls to parent class.
tuple () It is used to create a tuple in Python.
vars () It returns attributes for a class or module or any other object.
zip () It is used to create an iterator.

 

Python programming User defined functions

In this section, the advantages, uses and examples of user defined functions will be demonstrated.

The functions that are defined by the user are referred to as the user defined functions. The function definition and calling a function has already been discussed in the previous section.

 

Advantages of Functions

  1. User defined functions reduce the size of the program and make the program more easy to understand and modify. They are the small segments of a program that performs certain task.
  2. Functions are used when certain lines of code are needed a number of times. Hence by calling we can use those specific lines of code a number of times.
  3. By making functions or modules the work load on programmers can be reduced.

EXAMPLE of user defined function

Consider the following example in which a function is defined and it also returns a value:

CODE

>>> def add(a, b):

          c = a + b

          return c

>>> print(“The sum of a and b is”)

>>> print(add(4, 5))

OUTPUT

The sum of a and b is

9

the-sum-of-a-and-b

In the above example, a function is defined with a name add that has two arguments. In the function the value after addition of a and b is stored in the variable c and in the next line c is returned. Outside the body of the function first print statement is used to simply print a statement and in the next print statement we called the function by passing the values of the parameters, the function returns the value in the print statement and the value is printed.

The names of the modules or functions should be according to their functionality. This helps the programmers know that what this function is about.