Python Functions – [ Complete Guide ]

A python function is a small piece of code that is designed to perform a particular task. Python function are divided into two major categories

  1. Built-in function
  2. Methods
  3. User-Defined function

Built-in library functions are accessible directly without any type of import. These functions are available  with python compiler

Len(), input(), print() are few example of built-in function. I think you are well aware of the uses of input() and print() function.

Len() function is also a built-in function and you can use this function on more than one data type. Like this function find out the total number of characters in the string but return total elements available in a list.

Another type of function that only operate on a particular data type is known as methods like append(), sort, sum, sort are the methods available with the list only.  Thus these are known as methods.

Instead of all these available functions and methods we also need functions so that we can fulfill user-defined problems.  These functions are generated by users thus they are known as user-defined functions.

The syntax of a user-defined function is as follows

Def   function_name(parameters ):
   Function statements
   -------------------
   -------------------
[return]
Where
def                                         : it is compulsory to define a function
parameter                          :  It is optional
function_name                 : It is a valid identifier
function statement         :  any valid python statement

A sample of a user-defined  function

def  print_hello():
    print(‘Hello’*10)

In order to invoke/execute this function, you have to call this function.

print_hello()

Explanation

The name of the function in the above statement is  – print_hello
The function does not have any parameter and does not have any return value.
The output

Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello

Function Parameter in Python

def  addition(a,b):
      return a+b

Python function can also accept a parameter as any other programming language but the data type is not defined in the function prototype. The advantage of this is it automatically adapts the data type at the run time and returns the values accordingly.

The above function can be called with the following data type.

result = addition(10, 20)
print(result)
result = addition('rakesh', ' You are awesome')
print(result)
result = addition(20, 30.45)
print(result)
result = addition([10, 20, 30], [40, 50, 60])
print(result)
result = addition((10, 20, 30), (40, 50, 60))
print(result)

The output

30
rakesh You are awesome
50.45
[10, 20, 30, 40, 50, 60]
(10, 20, 30, 40, 50, 60)

What will happen when you forgot to pass second parameter in this function? Obvisously the function will crash automatically and raise an exception. Exception handling in Python

Another method to solve this situation is – passing default values to its parameter.

def addition(a, b=0):
    return a+b

result = addition(10)
print(result)
result = addition('rakesh', ' You are awesome')
print(result)
result = addition(20, 30.45)
print(result)
result = addition([10, 20, 30], [40, 50, 60])
print(result)
result = addition((10, 20, 30), (40, 50, 60))
print(result)

Now check the output of the above program

10
rakesh You are awesome  
50.45
[10, 20, 30, 40, 50, 60]
(10, 20, 30, 40, 50, 60)

NOTE: Please not that we can not use this function with single parameter at run time with all type of parameter.

Positional Arguments

Positional arguments are also supported by python functions. Lets check the following python function for positional parameters.

def display(number, msg1="School", msg2="Place"):
    print('-----Times :', number, end=" ")
    print('-----Message 1 :', msg1*2)
    print('-----Message 2 :', msg2)
    print('----------------------')


display(2, 'DAV', 'Ghaziabad')
display(5)
display("SpringDales")
display(msg2="Modern", number=3)
display(msg2="Modern", msg1=24, number=3)

Now check the prorgam very carefully. We are able to pass arguments at any position using the argument name with any position. The function is smart enough to check the actual arguments.
Output

-----Times : 2 -----Message 1 : DAVDAV
-----Message 2 : Ghaziabad
----------------------
-----Times : 5 -----Message 1 : SchoolSchool
-----Message 2 : Place
----------------------
-----Times : SpringDales -----Message 1 : SchoolSchool
-----Message 2 : Place
----------------------
-----Times : 3 -----Message 1 : SchoolSchool
-----Message 2 : Modern
----------------------
-----Times : 3 -----Message 1 : 48
-----Message 2 : Modern
----------------------

Passing list as a function parameter

List can also pass as a function arguments. The following program accepts two list as arguments an return only those elements thats are common.

def common(l1, l2):
    c = list()
    for x in l1:
        if x in l2:
            c.append(x)
    return c


l1 = [1, 2, 3, 4, 6, 8, 9]
l2 = [2, 4, 6, 7, 9, 10]

print(common(l1, l2))

The output of the above code is

[2, 4, 6, 9]

These are the basics of functions in Python. Besides these basics, you are also required to learn local variable and global variables in Python.

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.