Python Functions - Learn Python with Me - i-Sapna

Python Functions

A function is more like a program with instructions to carry out a task/mission. We have seen programs already that perform several tasks so far in our blog, but not the Python functions. Unlike the typical programs with the entire code to do several tasks, the functions usually have only blocks of code for a particular task. For example, Python’s print() and sqrt () are built-in functions, and we have used them in our earlier chapters. For your information, while the former is used to print the output on the screen, the latter is used to find the square root.

Nevertheless, as mentioned above, these are user-defined functions. In programming, one cannot just rely on the built-in functions to carry out all tasks. For specific challenging tasks, you might want to create your own functions. In Python, we call this concept creating user-defined functions.

5 Advantages of Python Functions

Python Functions Advantages
  • One of the significant advantages of Python Functions is that it reduces the size of code in a project. For example, if you define a function to add numbers, you can use it any number of times in your project without having to type the entire logic every single time.
  • The maintenance of the code gets easier through Python Functions. If a newer version of Python is released, and if your project wants to use it, you can do so by defining it in a new function. Similarly, you can also remove any feature that’s obsolete by removing its corresponding function.
  • If any error occurs in a function, you can update only the erred function without making changes in all the locations of the program. However, you might have to make some other changes as well accordingly.
  • Functions support the concept of modularity. For those of you who do not know, a module means a part of a program. It means that you can divide programs into modules with subtasks. Each module is defined by Functions.
  • If you write a function once, you can reuse it anytime based on your requirement. In layperson terms, you can also call functions a reusable code.

Python Functions and Methods Difference

Functions Methods 
Functions do not require a class to be defined in the program. A function that is present in a class is called a Method. 
Functions are independent. Methods depend on the class. 
Functions are not related to any object. Methods depend on the object of the class in which they are present. 
Functions do not require any arguments such as self. They can have many arguments or no arguments at all as per your choice. Methods should contain self as the first argument. 
A function is invoked just by its name. Methods are usually called on an object. 

How to define Python Functions?

In Python, you can define a function by using the keyword def followed by the function’s name. After the function name ends, you should add parentheses () to show that you declare a function and not a variable. You can choose to either pass parameters or declare a function without parameters with empty parentheses. You should add a ‘colon :’ after the parentheses end to represent the beginning of the function.

After the colon (:), we add the logic statements as mentioned in the format below. You can also add Docstring enclosed in three quotes to comment on what the function is all about, and this will be helpful when you create an API (Application Programming Interface) documentation file as mentioned in one of the earlier chapters on Docstrings.


Find the link to all chapters of Python: Learn Python


#function with parameters
def nameoffunction(parameter1,parameter2):
    """Docstring of function"""
    #statements of function

#function without parameters
def functionwithoutparameters():
    """Docstring of function"""
    #statements of function

Let us now create two functions – one that takes two parameters and the other that does not take any parameter.

def addition(a,b):
    """This function performs the add logic on two parameters"""
    c=a+b
    print("The result is: ",c)

#function to only print a sentence as output
def outputeg():
    """This function prints output without taking any parameters"""
    print("This sentence is printed from output function")

In the examples mentioned above, we have created two functions, addition and outputeg. While the former takes in two parameters to perform the addition operation with the logic added within its block, the latter does not take any parameter and displays the output as per its logic. You can use the addition function to perform additional operations by passing any two numbers when calling the function. Furthermore, you can use the outputeg function to print any sentence as output without passing any parameters.

Now that you know how to define a function let us learn about how you can call it in your Python programs.

How to call Python Functions?

When you define a function, you cannot expect it to run on its own. You must call the function to let it perform its task. If you would call a function that expects parameters, you should pass the parameters while calling the function, and you should not pass any parameter for those functions that are not expecting any parameters.

#DEFINING FUNCTIONS
#function to add two numbers
def addition(a,b):
    """This function performs the add logic on two parameters"""
    c=a+b
    print("The result is: ",c)

#function to only print a sentence as output
def outputeg():
    """This function prints output without taking any parameters"""
    print("This sentence is printed from output function")

#CALLING FUNCTIONS
addition(50,25)
outputeg()

Output

The result is:  75
This sentence is printed from output function

In the program above, we again defined the same functions and called them to pass two numbers and print the desired output. You can refer to the section of code after the comment #CALLING FUNCTIONS for the same.

Since the addition(a,b) function expects two variables, we passed numbers 50 and 25. These two numbers get assigned to the variables ‘a’ and ‘b’, and its result of a+b is then saved to the variable ‘c’ as per the statement in this function block. Finally, the ‘c’ variable is printed along with the text when the following line of the print statement is executed. This is what happens when the addition(a,b) function is called.

On the other hand, while calling the outputeg() function, we do not pass any parameters as this function is not expecting any parameters. However, the logic statements added in the outputeg() function block gets executed, and as you know, we have a print() function there. The same print() function gets executed when the outputeg() function is called.

How to return results from a function?

We can return the output from a function using the ‘return’ keyword. If you use the return keyword, you do not necessarily have to add the print() function again within the function.

#DEFINING FUNCTIONS
#function to add two numbers
def addition(a,b):
    """This function performs the add logic on two parameters"""
    c=a+b
    return c #returns the result c

#passing the parameters to addition function
#and printing the result
print("The result is",addition(50,25))

Output

The result is 75

You can notice that I have replaced the print statement with the return statement by adding ‘return c’. As you know, the result of a+b gets stored in c, and using the ‘return c’ statement, the value stored in the variable c is passed out wherever the addition(a,b) function is called. Since we called it once in a print statement, the value stored in the variable ‘c’, which is 75, gets displayed within this print statement and displays the output.

Returning Multiple Values in Python Functions

In the example program above, we saw a function returning one value. This is a typical characteristic of other programming languages as well. However, unlike its competition, Python allows you to return multiple values, and it returns multiple values in tuples.

def addition_subtraction(a,b):
    """We will use this function to
    return the results of both addition
    and subtraction..."""
    c=a+b
    d=a-b
    return c,d

#get results using the addition_subtraction function
p,q=addition_subtraction(50,25)
#printing the results
print("The addition result is: ",p)
print("The subtraction result is: ",q)

Output

The addition result is: 75
The subtraction result is: 25

Few Additional things about Python Functions

  • Functions are represented as ‘first class objects’ in Python. 
  • When you create a function, the Python Interpreter creates an object internally. 
  • You can pass a function as a value or an object to another function. 
  • You can also return a function to another function. 
#Python program to assign function to a variable
#define the function by adding variable
def output(name):
    return 'Hello '+name

#assign function to variable p
p=output("i-Sapna")
print(p)

Output

Hello i-Sapna

#Python program to define function inside another function
def result(name):
    def result_message():
        return 'Are you ok? '
    res=result_message()+name
    return res

#call result function
print(result("Sachin"))

Output

Are you ok? Sachin
Scroll to Top