Python - Functions



A Python function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

A top-to-down approach towards building the processing logic involves defining blocks of independent reusable functions. A Python function may be invoked from any other function by passing required data (called parameters or arguments). The called function returns its result back to the calling environment.

python functions

Types of Python Functions

Python provides the following types of functions −

Python's standard library includes number of built-in functions. Some of Python's built-in functions are print(), int(), len(), sum(), etc. These functions are always available, as they are loaded into computer's memory as soon as you start Python interpreter.

The standard library also bundles a number of modules. Each module defines a group of functions. These functions are not readily available. You need to import them into the memory from their respective modules.

In addition to the built-in functions and functions in the built-in modules, you can also create your own functions. These functions are called user-defined functions.

Defining a Python Function

You can define custom functions to provide the required functionality. Here are simple rules to define a function in Python.

  • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).

  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.

  • The first statement of a function can be an optional statement; the documentation string of the function or docstring.

  • The code block within every function starts with a colon (:) and is indented.

  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Syntax to Define a Python Function

def functionname( parameters ):
   "function_docstring"
   function_suite
   return [expression]

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

Once the function is defined, you can execute it by calling it from another function or directly from the Python prompt.

Example to Define a Python Function

The following example shows how to define a function greetings(). The bracket is empty so there aren't any parameters.

The first line is the docstring. Function block ends with return statement. when this function is called, Hello world message will be printed.

def greetings():
   "This is docstring of greetings function"
   print ("Hello World")
   return

greetings()

Calling a Python Function

Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt.

Example to Call a Python Function

Following is the example to call printme() function −

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print (str)
   return;

# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following output

I'm first call to user defined function!
Again second call to the same function

Pass by Reference vs Value

The function calling mechanism of Python differs from that of C and C++. There are two main function calling mechanisms: Call by Value and Call by Reference.

When a variable is passed to a function, what does the function do to it? If any changes to its variable doesnot get reflected in the actual argument, then it uses call by value mechanism. On the other hand, if the change is reflected, then it becomes call by reference mechanism.

Pass By Reference Vs Value

C/C++ functions are said to be called by value. When a function in C/C++ is called, the value of actual arguments is copied to the variables representing the formal arguments. If the function modifies the value of formal aergument, it doesn't reflect the variable that was passed to it.

Python uses pass by reference mechanism. As variable in Python is a label or reference to the object in the memory, the both the variables used as actual argument as well as formal arguments really refer to the same object in the memory. We can verify this fact by checking the id() of the passed variable before and after passing.

def testfunction(arg):
   print ("ID inside the function:", id(arg))

var="Hello"
print ("ID before passing:", id(var))
testfunction(var)

If the above code is executed, the id() before passing and inside the function is same.

ID before passing: 1996838294128
ID inside the function: 1996838294128

The behaviour also depends on whether the passed object is mutable or immutable. Python numeric object is immutable. When a numeric object is passed, and then the function changes the value of the formal argument, it actually creates a new object in the memory, leaving the original variable unchanged.

def testfunction(arg):
   print ("ID inside the function:", id(arg))
   arg=arg+1
   print ("new object after increment", arg, id(arg))

var=10
print ("ID before passing:", id(var))
testfunction(var)
print ("value after function call", var)

It will produce the following output

ID before passing: 140719550297160
ID inside the function: 140719550297160
new object after increment 11 140719550297192
value after function call 10

Let us now pass a mutable object (such as a list or dictionary) to a function. It is also passed by reference, as the id() of lidt before and after passing is same. However, if we modify the list inside the function, its global representation also reflects the change.

Here we pass a list, append a new item, and see the contents of original list object, which we will find has changed.

def testfunction(arg):
   print ("Inside function:",arg)
   print ("ID inside the function:", id(arg))
   arg=arg.append(100)
   
var=[10, 20, 30, 40]
print ("ID before passing:", id(var))
testfunction(var)
print ("list after function call", var)

It will produce the following output

ID before passing: 2716006372544
Inside function: [10, 20, 30, 40]
ID inside the function: 2716006372544
list after function call [10, 20, 30, 40, 100]

Python Function Arguments

The process of a function often depends on certain data provided to it while calling it. While defining a function, you must give a list of variables in which the data passed to it is collected. The variables in the parentheses are called formal arguments.

When the function is called, value to each of the formal arguments must be provided. Those are called actual arguments.

function arguments

Example

Let's modify greetings function and have name an argument. A string passed to the function as actual argument becomes name variable inside the function.

def greetings(name):
   "This is docstring of greetings function"
   print ("Hello {}".format(name))
   return
   
greetings("Samay")
greetings("Pratima")
greetings("Steven")

It will produce the following output

Hello Samay
Hello Pratima
Hello Steven

Types of Python Function Arguments

Based on how the arguments are declared while defining a Python function, they are classified into the following categories −

In the next few chapters, we will discuss these function arguments at length.

Order of Python Function Arguments

A function can have arguments of any of the types defined above. However, the arguments must be declared in the following order −

  • The argument list begins with the positional-only args, followed by the slash (/) symbol.

  • It is followed by regular positional args that may or may not be called as keyword arguments.

  • Then there may be one or more args with default values.

  • Next, arbitrary positional arguments represented by a variable prefixed with single asterisk, that is treated as tuple. It is the next.

  • If the function has any keyword-only arguments, put an asterisk before their names start. Some of the keyword-only arguments may have a default value.

  • Last in the bracket is argument with two asterisks ** to accept arbitrary number of keyword arguments.

The following diagram shows the order of formal arguments −

Order Of Formal Arguments

Python Function with Return Value

The return keyword as the last statement in function definition indicates end of function block, and the program flow goes back to the calling function. Although reduced indent after the last statement in the block also implies return but using explicit return is a good practice.

Along with the flow control, the function can also return value of an expression to the calling function. The value of returned expression can be stored in a variable for further processing.

Example

Let us define the add() function. It adds the two values passed to it and returns the addition. The returned value is stored in a variable called result.

def add(x,y):
   z=x+y
   return z

a=10
b=20
result = add(a,b)
print ("a = {} b = {} a+b = {}".format(a, b, result))

It will produce the following output −

a = 10 b = 20 a+b = 30
Advertisements