top
upGrad KnowledgeHut SkillFest Sale!

Search

Python Tutorial

Python's standard distribution consists of a large number of functions. Some are always available for use as they are loaded every time when Python interpreter starts. Others may be loaded as and when required from the built-in modules bundled in the distribution itself. Each of these functions performs a predefined task and can be called upon in any program as per requirement.However, the user (programmer) is free to define a new function if required. Such a function is known as a User Defined Function. Just as we can import a function from built-in module, a user-defined function in one script can be imported in another script. It is also possible to make such script available for system-wide use or even for other users by uploading to Python Package Index (PyPI). First we shall learn how to define and then use it in Python program.Defining functionAs we learned earlier, a function is a reusable block of statements performing a single task. A new function is defined using 'def' keyword. You can give it any suitable name (the name should follow the rules of naming an identifier). The name of your function after def keyword should have parentheses. The block Python statements to perform required task is entered with increased indent. To start the block you have to type ':' symbol after the parentheses.Many a times, some parameters need to be provided to the function to perform its task. In such cases, these parameters are mentioned inside parentheses. Otherwise parentheses may be empty.Given below is a prototype definition of functiondef function([p1],[p2],…):        "function docstring"        statement1        statement2        ..        ..        return [expression]The keyword def is followed by a suitable identifier as name of function and parentheses. One or more parameters may be optionally mentioned inside parentheses. The : symbol after parentheses starts an indented block.First statement in this block is an optional string literal which provides description about functionality. It is called docstring and is somewhat similar to comment. It is not executed, but is a part of function object attributes in the form of function.__doc__.Subsequent statements that perform a certain task form body of the function. It may be a variable declaration, expressions, conditionals, loop or even another function declaration inside it.Last statement in the function block has return keyword. It sends execution control back to the position in the program from where it was called. Following diagram will explain this behaviour.The return statement is optional. Even if it is not used, flow of program goes back. However, if it is required that it should carry with it certain expression while returning, an value of expression put in front of it is returned.Given below is definition of greetings() function.>>> def greetings(): "First line in function is DocString" print("Hello EveryOne") returnWhen this function is called, it will print a greeting message.>>> greetings() Hello EveryOneIf the function contains a string literal as its first line, it is treated as docstring and serves as value of __doc__ attribute of function object.>>> greetings.__doc__ 'First line in function is DocString'Passing parameters to FunctionAs mentioned above, process defined inside a function may depend upon one or more parameters. Hence it should be designed that way to receive one or more parameters (also called arguments) mentioned inside parentheses after its name. These parameters/arguments may be given suitable formal names.In the greetings() function we now define a string parameter called name.>>> def greetings(name): "First line in function is DocString" print("Hello {}".format(name)) returnWhen calling the function required parameter is now passed to it.>>> greetings("World") Hello World >>> greetings("Bengaluru") Hello BengaluruArguments in definition of function are called formal arguments/parameters. Data items passed to the function become actual arguments/parameters.Instead of defining and calling function in Python console, one can put it in a Python script and run it from command prompt or from inside an IDE like IDLE.In following example, add() function is defined with two parameters. It calculates their total. The function is called by providing same number of parameters.def add(x, y):    ttl=x+y    print ("addition = {}".format(ttl))    return num1=int(input("Enter first number: ")) num2=int(input("Enter second number: ")) add(num1,num2)Save above script as add.pyOutput of above code with two different set of inputs is shown below:Enter first number: 10 Enter second number: 20 addition = 30 Enter first number: 100 Enter second number: 200 addition = 300Default value of parameterOne or more parameters in a function may be defined to have a default value. If while calling such function, required parameter is not passed, the default value will be processed.In the greetings() function defined earlier, the 'name' parameter is now set to a default value 'World'. If any value is explicitly passed, the default will be overridden. If no value is passed, the default is used.>>> def greetings(name="World"): "First line in function is DocString" print("Hello {}".format(name)) return >>> greetings("Mumbai") Hello Mumbai >>> greetings() Hello WorldKeyword argumentsNumber and type of parameter must match with the values passed to the function. If not, error may be encountered. In add.py script used earlier, add() function needs two parameters of numeric type. However, if only one parameter is passed, error is generated as showndef add(x, y):    ttl=x+y    print ("addition = {}".format(ttl))    return add(10,20) add(10)Output:addition = 30 Traceback (most recent call last):  File "C:\python36\add.py", line 7, in <module>    add(10) TypeError: add() missing 1 required positional argument: 'y'First call to the function is ok as two required parameters are passed. In second call, there is one parameter less.Even if number of values passed is same as that of arguments but if their respective types don't match, TypError message is still displayed.For instance passing number and a string to add() function is not accepted as shown below:def add(x, y):   ttl=x+y    print ("addition = {}".format(ttl))    return add(10, "Hello")Output:Traceback (most recent call last):  File "C:\python36\add.py", line 6, in <module>    add(10, "Hello")  File "C:\python36\tmp.py", line 2, in add    ttl=x+y TypeError: unsupported operand type(s) for +: 'int' and 'str'Let us define a divide() function with two numeric objects as arguments.def divide(n, d):    div=n/d    print ("division = {}".format(div))    returnFor divide() function, n and d are the positional arguments. Hence, first value passed to it will become n and second becomes d.Python provides a useful mechanism of using argument in definition as keyword in function call. The function will process the arguments even if they are not in order of definition.Second call to div() function is uses keyword arguments.def divide(n, d):    div=n/d    print ("division = {}".format(div))    return #positional arguments divide(10, 5) #keyword arguments divide(d=10, n=100)Output:division = 2.0 division = 10.0Function with return valueAny function is one component of the entire program which may have many such functions. Most of the times, we need the output of one function to be processed in other. Hence when a function returns, it should also return a value.Most of the built-in functions return some value. The len() function returns length of sequence.>>>string='Hello World' >>> chars=len(string) >>>chars 11In order to make a function return certain value, put an expression front of return statement. Value of this expression may be assigned to some variable for subsequent processing.def add(x, y):     ttl=x+y     return ttl a=10 b=20 c=add(a,b) print ("addition of {} and {} is {}".format(a,b,c))Output:addition of 10 and 20 is 30Local and global variablesA variable defined inside function is not accessible outside it. Such variable is called a local variable. Formal arguments also behave as local variable inside the function. Attempt to access a local variable outside its scope will result in NameErrordef add(x, y):    ttl=x+y add(10,20) print ("total=",ttl)Here, ttl is local variable for add() function and is not accessible to print statement outside it. Output of above code on Python console is like this:Traceback (most recent call last):  File "C:\python36\add.py", line 5, in <module>    print ("total=",ttl) NameError: name 'ttl' is not definedIf a variable is defined outside any function block its value is accessible from inside any function. It is called as a global variable. In following code snippet, ttl is defined before function. Hence it is a global variable.ttl=50 def add(x, y):        print ("ttl is a global variable")        print ("total=",ttl) add(10,20)Output of above code is:ttl is a global variable Total :  50However, if we initialize variable of same name inside the function, a new local variable is created. This assignment will not alter value of global variable.ttl=50 def add(x, y):        ttl=x+y        print ("ttl is local variable")        print ("total=",ttl) add(10,20) print ("ttl is global variable") print ("total=",ttl)Output shows that globally declared ttl will continue to have earlier value.ttl is local variable total= 30 ttl is global variable total= 50To modify value of global variable from within a function, it has to be accessed by using 'global' keyword.ttl=50 def add(x, y):        global ttl        ttl=x+y        print ("modifying global variable in function")        print ("total=",ttl) add(10,20) print ("ttl is global variable") print ("total=",ttl)Here’s the outputmodifying global variable in function total= 30 ttl is global variable total= 30Python's built-in function global() returns a dictionary object of all global variables keys and their respective values. In following code same name is used as global and local variable.ttl=50 def add(x, y):        ttl=x+y        globals()['ttl']=ttl        print ("modifying global variable in function")        print ("total (local variable) =",ttl)     add(10,20) print ("ttl is global variable") print ("total=",ttl)Here 'ttl' is used as key and globals()['ttl'] retrieves value of globally declared ttl variable.modifying global variable in function total (local variable) = 30 ttl is global variable total= 30Passing arguments by reference:As explained earlier, variable in Python is a reference to the object in memory. H, both formal and actual arguments refer to same object. Following snippet will confirm this:def function(x):        print ("value {} id {} of argument".format(x,id(x))) a=10 print ("value {} id {} of passed value".format(a,id(a))) function(a)The id() function returns a unique integer corresponding to identity of an object. In above code, id() of object before and after passing is same, which means objects are always passed by reference to a function in Python.value 10 id 1897295152 of passed value value 10 id 1897295152 of argumentIt also means that if argument object is modified inside the function, the changes should be reflected outside the function as well. In following program a list object is passed to append() function. Changes made to the list by the function are reflected in the list object.def append(list):        list.append(60)        print ("changed list inside function: ", list)        return numbers=[10,20,30,40,50] print ("list before passing: ", numbers) append(numbers) print ("list after returning from function: ", numbers)pass by reference feature of Python function is confirmed by following output:list before passing:  [10, 20, 30, 40, 50] changed list inside function:  [10, 20, 30, 40, 50, 60] list after returning from function:  [10, 20, 30, 40, 50, 60]
logo

Python Tutorial

Python - User Defined Functions

Python's standard distribution consists of a large number of functions. Some are always available for use as they are loaded every time when Python interpreter starts. Others may be loaded as and when required from the built-in modules bundled in the distribution itself. Each of these functions performs a predefined task and can be called upon in any program as per requirement.

However, the user (programmer) is free to define a new function if required. Such a function is known as a User Defined Function. Just as we can import a function from built-in module, a user-defined function in one script can be imported in another script. It is also possible to make such script available for system-wide use or even for other users by uploading to Python Package Index (PyPI). First we shall learn how to define and then use it in Python program.

Defining function

As we learned earlier, a function is a reusable block of statements performing a single task. A new function is defined using 'def' keyword. You can give it any suitable name (the name should follow the rules of naming an identifier). The name of your function after def keyword should have parentheses. The block Python statements to perform required task is entered with increased indent. To start the block you have to type ':' symbol after the parentheses.

Many a times, some parameters need to be provided to the function to perform its task. In such cases, these parameters are mentioned inside parentheses. Otherwise parentheses may be empty.

Given below is a prototype definition of function

def function([p1],[p2],…):
       "function docstring"
       statement1
       statement2
       ..
       ..
       return [expression]

The keyword def is followed by a suitable identifier as name of function and parentheses. One or more parameters may be optionally mentioned inside parentheses. The : symbol after parentheses starts an indented block.

First statement in this block is an optional string literal which provides description about functionality. It is called docstring and is somewhat similar to comment. It is not executed, but is a part of function object attributes in the form of function.__doc__.

Subsequent statements that perform a certain task form body of the function. It may be a variable declaration, expressions, conditionals, loop or even another function declaration inside it.

Last statement in the function block has return keyword. It sends execution control back to the position in the program from where it was called. Following diagram will explain this behaviour.User Defined Functions in python

The return statement is optional. Even if it is not used, flow of program goes back. However, if it is required that it should carry with it certain expression while returning, an value of expression put in front of it is returned.

Given below is definition of greetings() function.

>>> def greetings():
"First line in function is DocString"
print("Hello EveryOne")
return

When this function is called, it will print a greeting message.

>>> greetings()
Hello EveryOne

If the function contains a string literal as its first line, it is treated as docstring and serves as value of __doc__ attribute of function object.

>>> greetings.__doc__
'First line in function is DocString'

Passing parameters to Function

As mentioned above, process defined inside a function may depend upon one or more parameters. Hence it should be designed that way to receive one or more parameters (also called arguments) mentioned inside parentheses after its name. These parameters/arguments may be given suitable formal names.

In the greetings() function we now define a string parameter called name.

>>> def greetings(name):
"First line in function is DocString"
print("Hello {}".format(name))
return

When calling the function required parameter is now passed to it.

>>> greetings("World")
Hello World
>>> greetings("Bengaluru")
Hello Bengaluru

Arguments in definition of function are called formal arguments/parameters. Data items passed to the function become actual arguments/parameters.

Instead of defining and calling function in Python console, one can put it in a Python script and run it from command prompt or from inside an IDE like IDLE.

In following example, add() function is defined with two parameters. It calculates their total. The function is called by providing same number of parameters.

def add(x, y):
   ttl=x+y
   print ("addition = {}".format(ttl))
   return
num1=int(input("Enter first number: "))
num2=int(input("Enter second number: "))
add(num1,num2)

Save above script as add.py

Output of above code with two different set of inputs is shown below:

Enter first number: 10
Enter second number: 20
addition = 30
Enter first number: 100
Enter second number: 200
addition = 300

Default value of parameter

One or more parameters in a function may be defined to have a default value. If while calling such function, required parameter is not passed, the default value will be processed.

In the greetings() function defined earlier, the 'name' parameter is now set to a default value 'World'. If any value is explicitly passed, the default will be overridden. If no value is passed, the default is used.

>>> def greetings(name="World"):
"First line in function is DocString"
print("Hello {}".format(name))
return
>>> greetings("Mumbai")
Hello Mumbai
>>> greetings()
Hello World

Keyword arguments

Number and type of parameter must match with the values passed to the function. If not, error may be encountered. In add.py script used earlier, add() function needs two parameters of numeric type. However, if only one parameter is passed, error is generated as shown

def add(x, y):
   ttl=x+y
   print ("addition = {}".format(ttl))
   return
add(10,20)
add(10)

Output:

addition = 30
Traceback (most recent call last):
 File "C:\python36\add.py", line 7, in <module>
   add(10)
TypeError: add() missing 1 required positional argument: 'y'

First call to the function is ok as two required parameters are passed. In second call, there is one parameter less.

Even if number of values passed is same as that of arguments but if their respective types don't match, TypError message is still displayed.

For instance passing number and a string to add() function is not accepted as shown below:

def add(x, y):
  ttl=x+y
   print ("addition = {}".format(ttl))
   return
add(10, "Hello")

Output:

Traceback (most recent call last):
 File "C:\python36\add.py", line 6, in <module>
   add(10, "Hello")
 File "C:\python36\tmp.py", line 2, in add
   ttl=x+y
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Let us define a divide() function with two numeric objects as arguments.

def divide(n, d):
   div=n/d
   print ("division = {}".format(div))
   return

For divide() function, n and d are the positional arguments. Hence, first value passed to it will become n and second becomes d.

Python provides a useful mechanism of using argument in definition as keyword in function call. The function will process the arguments even if they are not in order of definition.

Second call to div() function is uses keyword arguments.

def divide(n, d):
   div=n/d
   print ("division = {}".format(div))
   return
#positional arguments
divide(10, 5)
#keyword arguments
divide(d=10, n=100)

Output:

division = 2.0
division = 10.0

Function with return value

Any function is one component of the entire program which may have many such functions. Most of the times, we need the output of one function to be processed in other. Hence when a function returns, it should also return a value.

Most of the built-in functions return some value. The len() function returns length of sequence.

>>>string='Hello World'
>>> chars=len(string)
>>>chars
11

In order to make a function return certain value, put an expression front of return statement. Value of this expression may be assigned to some variable for subsequent processing.User Defined Functions in python

def add(x, y):
    ttl=x+y
    return ttl
a=10
b=20
c=add(a,b)
print ("addition of {} and {} is {}".format(a,b,c))

Output:

addition of 10 and 20 is 30

Local and global variables

A variable defined inside function is not accessible outside it. Such variable is called a local variable. Formal arguments also behave as local variable inside the function. Attempt to access a local variable outside its scope will result in NameError

def add(x, y):
   ttl=x+y
add(10,20)
print ("total=",ttl)

Here, ttl is local variable for add() function and is not accessible to print statement outside it. Output of above code on Python console is like this:

Traceback (most recent call last):
 File "C:\python36\add.py", line 5, in <module>
   print ("total=",ttl)
NameError: name 'ttl' is not defined

If a variable is defined outside any function block its value is accessible from inside any function. It is called as a global variable. In following code snippet, ttl is defined before function. Hence it is a global variable.

ttl=50
def add(x, y):
       print ("ttl is a global variable")
       print ("total=",ttl)
add(10,20)

Output of above code is:

ttl is a global variable
Total :  50

However, if we initialize variable of same name inside the function, a new local variable is created. This assignment will not alter value of global variable.

ttl=50
def add(x, y):
       ttl=x+y
       print ("ttl is local variable")
       print ("total=",ttl)
add(10,20)
print ("ttl is global variable")
print ("total=",ttl)

Output shows that globally declared ttl will continue to have earlier value.

ttl is local variable
total= 30
ttl is global variable
total= 50

To modify value of global variable from within a function, it has to be accessed by using 'global' keyword.

ttl=50
def add(x, y):
       global ttl
       ttl=x+y
       print ("modifying global variable in function")
       print ("total=",ttl)
add(10,20)
print ("ttl is global variable")
print ("total=",ttl)

Here’s the output

modifying global variable in function
total= 30
ttl is global variable
total= 30

Python's built-in function global() returns a dictionary object of all global variables keys and their respective values. In following code same name is used as global and local variable.

ttl=50
def add(x, y):
       ttl=x+y
       globals()['ttl']=ttl
       print ("modifying global variable in function")
       print ("total (local variable) =",ttl)    
add(10,20)
print ("ttl is global variable")
print ("total=",ttl)

Here 'ttl' is used as key and globals()['ttl'] retrieves value of globally declared ttl variable.

modifying global variable in function
total (local variable) = 30
ttl is global variable
total= 30

Passing arguments by reference:

As explained earlier, variable in Python is a reference to the object in memory. H, both formal and actual arguments refer to same object. Following snippet will confirm this:

def function(x):
       print ("value {} id {} of argument".format(x,id(x)))
a=10
print ("value {} id {} of passed value".format(a,id(a)))
function(a)

The id() function returns a unique integer corresponding to identity of an object. In above code, id() of object before and after passing is same, which means objects are always passed by reference to a function in Python.

value 10 id 1897295152 of passed value
value 10 id 1897295152 of argument

It also means that if argument object is modified inside the function, the changes should be reflected outside the function as well. In following program a list object is passed to append() function. Changes made to the list by the function are reflected in the list object.

def append(list):
       list.append(60)
       print ("changed list inside function: ", list)
       return
numbers=[10,20,30,40,50]
print ("list before passing: ", numbers)
append(numbers)
print ("list after returning from function: ", numbers)

pass by reference feature of Python function is confirmed by following output:

list before passing:  [10, 20, 30, 40, 50]
changed list inside function:  [10, 20, 30, 40, 50, 60]
list after returning from function:  [10, 20, 30, 40, 50, 60]

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Eula

This is my first time here. I am truly impressed to read all this in one place.

Jaypee Dela Cruz

Thank you for your wonderful codes and website, you helped me a lot especially in this socket module. Thank you again!

lucky verma

Thank you for taking the time to share your knowledge about using python to find the path! Your insight and guidance is greatly appreciated.

Pre Engineered Metal Building

Usually I by no means touch upon blogs however your article is so convincing that I by no means prevent myself to mention it here.

Pre Engineered Metal Building

Usually, I never touch upon blogs; however, your article is so convincing that I could not prevent myself from mentioning how nice it is written.

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More