Python Functions



The function is a collection of statement that performs a specific task.

The function executes when it is called by its name.

A large program is divided into many small building blocks for simplicity and this building block is called function.

We can call a function again and again.

The most important feature of function is code reusability.

def keyword is used to define a function in python.


Syntax

def function_name(arguments):
    function_body

def

def is a keyword that is used to define function.

function_name

function_name is the actual name of the function.

function_name is also used at the time of calling the function.

arguments

arguments are the place where we can pass many parameters/variables. These variables may be used in the program.

The value of the parameter is passed from the calling of function. It is an optional part.

function_body

function_body is the place where the actual code is written to perform the specific task.


Example

def add():
    a = 5
    b = 3
    c = a+b
    print("addition of a and b is :", c)

add()

Output

addition of a and b is : 8

Types of Arguments 

  • Positional Arguments
  • Keyword Arguments
  • Default Arguments
  • Variable Length Positional Arguments (*args)
  • Variable Length Keyword Arguments (**kwargs)

Function with arguments


Example

def add(a, b):
    c = a+b
    print("addition of a and b is :", c)

add(5, 6)

Output

addition of a and b is : 11

Function with default argument value

We can also assign a default value to an argument.

If the function is called without an argument, it uses the default value.


Example

def add(a=2, b=7):
    c = a+b
    print("addition of a and b is :", c)

add()
add(6)
add(3, 6)

Output

addition of a and b is : 9
addition of a and b is : 13
addition of a and b is : 9

Passing List as an Arguments

We can pass something like a list, tuple, dictionary...etc in the function.


Example

def subjects(myList):
    for l in myList:
        print("Subject", l)

myList = ["Python", "Django", "HTML", "CSS"]
subjects(myList)

Output

Subject Python
Subject Django
Subject HTML
Subject CSS

Function with return value

We can also return a value from the function using the return type. return keyword is used to return a value.


Example

def add(a, b):
    c = a+b
    return c

addition = add(3, 6)
print(addition)

Output

9

Arbitrary Arguments *args

If the number of arguments is unknown add an asterisk(*) symbol before the parameter name.

We can access the arguments using the index values.


Example

def subjects(*args):
    print("Subject", myList[0])
    print("Subject", myList[1])
    print("Subject", myList[2])

myList = ["Python", "Django", "HTML", "CSS"]
subjects(myList)

Output

Subject Python
Subject Django
Subject HTML

Arbitrary Keyword Arguments **kwargs

The **  syntax is similar, but it only works for keyword arguments. This gets them into a new dictionary, where the argument names are the keys, and their values are similar dictionary values.


Example

def subjects(**kwargs):
    print(kwargs)

subjects(name="Denny", subject="Python", age=21)

Output

{'name': 'Denny', 'subject': 'Python', 'age': 21}

Function with a pass statement

Pass statement is compulsory to define a function in python means we can not declare a function. So to define a function with no content pass statement is used.


Example 

def subject(name):
    pass


def subject(name):
    print(name)


subject("Python")

Output

Python

Function with a Docstring

Python Doctstring is the documentation string that occurs at the class, method, or function level.

A docstring is simply a multi-line string that is not assigned to anything. 

Docstring is generally the first statement in particular areas, and the code follows after it.

The docstring for any particular python object can be obtained by using a doc attribute for that object.


Example

def hello():
    """
        This Function Print the 
        "Hello World"
        on the Screen
    """
    print("Hello World")


hello()

Output

Hello World

Nested Functions

A Nested function is a function defined within another function. When performing complex tasks multiple times within another function, they are useful to avoid loops or code duplication.


Example

def add(a, b):
    def innerFun(c, d):
        return c + d
    return innerFun(a, b)


print(add(5, 6))

Output

11

Recursion

The process of calling a function by itself is called recursion.

The benefit of recursion is that we can use it as a loop.


Example

Factorial of any number using recursion

def factorial(num):
    if num > 1:
        return num * factorial(num-1)
    else:
        return 1


n = int(input("Enter any Number :"))
print(f"Factorial of {n} is ", factorial(n))

Output

Enter any Number :3
Factorial of 3 is  6