Skip to content

Function in Python – An Intro for beginners

Function in Python

Function In Python is a block of code, which is written to perform various computational, logical, etc. operations. In the function we can pass data as parameter. We can call any function as many times as we want.

There are usually two types of function in Python . They are as follows –

  • Built-in Function = Built-in function in Python are those functions which are pre-defined in Python . We can use all the built-in function after successfully install Python in our computer .
  • User-defined Function = User-defined function in Python are those function which are defined by any user to perform any specific task .

Here we will discuss about user-defined function.

Advantages of using Function in Python

Function in Python has the following advantages –

  • We can call any Python function multiple times in a program .
  • Python function helps us to implement a basic Programming principle DRY (Don’t Repeat Yourself) .
  • Python function helps us to avoid rewriting of same code again and again .
  • We can divide a large Python program into multiple small part using Python function .

Define a Function in Python

Python provides def keyword to define a function –

Syntax of a Function in Python:

def func_name(parameters):
    "function docstring"
    statements
    return

Structure of a Function in Python

Now we will understand the syntax of a function –

  • Any function in Python starts with def keyword followed by function name and a parentheses ().
  • In parentheses () we can pass data as a parameter . There can be any number of parameter in a Python function . We can also write function without any parameter .
  • Any function header will end with a colon (:) and the code block will be indented.
  • We can use docstring in the first line of a function statement . This is optional . With the help of docstring we will know for what reason the function is written .
  • Whenever a function face return keyword program will exit the function . But it is optional . If we do not use the return keyword then the function will automatically return None .

Calling a Function in Python

After defining a function if we want to implement the function in the program then we need to call the function . Before calling a function we must define the function otherwise it will raise an error .

Syntax of calling a Function in Python

func _name(arguments)

The return statement

The return keyword is generally used at the end of a function to return the result of the function . Actually return statement in Python function is optional . If we do not use return statement then Python automatically takes it as None . We can also use return statement in the middle of a function but whenever the program face the return statement it will exit immediately from the function .

Function in Python Examples

Example 1: Function without parameter and return statement

# define a function
def welcome():
    print("Welcome to Coding Conception")
    
# calling the function
print(welcome())
Welcome to Coding Conception
None
  • In the above code first we have defined a function named welcome which neither has any parameter nor has return statement . This function just prints a statement .
  • After that we have called the function inside the print() function . first welcome() function is executed and printed Welcome to Coding Conception in the output . As the welcome() function does not have any return statement so by default it takes return as None . For this reason print() function has printed None in the output .

Example 2: Function without parameter and with return statement

# define a function
def welcome():
    return "Welcome to Coding Conception"
    
# calling the function
print(welcome())
Welcome to Coding Conception
  • In the above code first we have defined a function named welcome which does not have any parameter but has return statement . This function just returns a statement .
  • After that we have called the function inside the print() function . first welcome() function is executed and returned Welcome to Coding Conception . After that print() function has printed the return value in the output .

Example 3: Function with parameter and without return statement

# defining a function to get sum of two numbers
def add (number1, number2):
    #function body
    number3 = number1 + number2
    print(number3)

#calling a function
print(add(5, 8))
13
None
  • In the above code, first we have defined a function add which takes two parameters number1 and number2 . Then the value of two parameters are added and stored in a new variable named number3 . After function calling number3 will be printed in the output .
  • Then the add() function has been called along with the print() function. The add() function has run and printed 13(5 + 8) in the output since the function definition has a print function. But with 13 , None has also been printed in the output because by default Python function takes return as None .

Example 4: Function with parameter and return statement

# defining a function to get sum of two numbers
def add (number1, number2):
    #function body
    number3 = number1 + number2
    return number3

#calling a function
print(add(4, 6))
10
  • In the above code, first we have defined a function add which takes two parameters number1 and number2 . Then the value of two parameters are added and stored in a new variable named number3 . After function calling number3 will be returned .
  • Then the add() function has been called along with the print() function. The add() function has run and returned 10(4 + 6) . After that print() function prints 10 in the output . .

Docstring in Function in Python

We can use docstring in the first line of any function statement, which will tell the function user why the function is written . The (__doc__) attribute helps us to know the docstring of a function.

#defining a function to greet someone
def greet (name):
    '''This function will greet anyone''' #docstring
    print("hello" + name)
    
print(greet.__doc__)  
This function will greet anyone

In the above code we have written a function called greet, in the first line of which we have written a docstring. Then we have printed the docstring of the function with the help of (__doc__) attribute.

Why we should not use Python keyword as Function name ?

We will try to understand the answer of the question with a simple example . Since len is a python keyword, we will create a function named len to show why python keyword should not be used as function name.

def len(number):
    return number*2

print(len(4))
print(len("python"))
8
pythonpython

In the above code we have written a function called len. Which multiplies the input with 2 and returns it. So when 4 is given as argument in len() function, it has returned 8 and when python is given as an argument it has returned pythonpython.

But in case of built-in len() function, we know that for integer input it raises an error and for string input it returns the length of the string .

Nested Function in Python

Nested function in Python means using a function inside another function .

Example : Define a nested function in Python

# nested function in python
# defining the outer function
def outer_func():
    print("This is an outer function")
    # defining the inner function
    def inner_func():
        print("This is an inner function")
    return inner_func()

# calling the outer function
outer_func()

# calling the inner_func
inner_func()
This is an outer function
This is an inner function
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_9656/3562563598.py in <module>
     12 
     13 # calling the inner_func
---> 14 inner_func()

NameError: name 'inner_func' is not defined

In the above code we have defined a function named outer_func which contains a function named inner_func .

After that we have called the outer_func() function which have done the below works-

  • At first It has printed This is an outer function in the output after facing the print() function in the first line .
  • Then as the 2nd line has comment and 3rd and 4th line has inner_func definition so nothing has been printed in the output .
  • Then in the 5th line inner_func() is returned . After that inner_func() is executed and printed This is an inner function in the output .

After that we have called inner_func() . As inner_func() is in the outer_func() so we can only access inner_func() inside the outer_func() . If we try to access inner_func() from any other area then it will raise error .

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply