8. Functions : Basics

What are Functions?

Function is one of the most important aspects of Python programming. A function is a set of code that does a particular task.

The Function helps programmers to break the program into smaller parts. It organizes the code very effectively and avoids repetition. As the program grows, a function makes the program more organized.

Imagine a Program where we need to do addition more than 100 times. To do an addition 100 times, we will have to write the same code 100 times.

A function can be of huge help here. Once we make a function of addition, we will call it every time we need to add.

Advantages of Functions in Python:

There are the following advantages of Python functions.

1. We can avoid rewriting the same logic/code again and again in a program. The reusability of code makes the program better.

2. We can call Python functions multiple times in a program and anywhere in a program.

3. We can track a large Python program easily when it is divided into multiple functions.

Types of a Function :

There are two types of Functions, explained below :

1. Built-in Functions:

Built-in functions are the functions that are predefined in Python. For Example : print() , type()

2. User-Defined Functions :

User-defined functions are the functions that a user defines for a particular task.

Two Important Aspects of a Function :

1. Defining a Function :

Defining a function means we need to define what specific task our function will do.

2. Calling a Function :

Calling a function means whenever we need to do the task, we need to call the function.

We cannot call a function before defining it.

Creating / Defining a Function:

Python provides the def keyword to define a function. The syntax of the define function is given below.

In [ ]:

def function_name():
    statement1
    statement2

Function to print Hello World:

In [1]:

def myfunc():
    print("hello world")

Now, if we try to run the above program, nothing happens. Because we have defined the function, but we haven't called it yet.

Calling a Function :

We can call a function simply with the help of this syntax :

So we will get the desired result by merging these two codes together.

In [2]:

#Defining a Function
def myfunc():
    print("hello world")

#Calling a Function
myfunc()

Parameters and Arguments in a Function :

Parameters are types of information that can be passed into the function. The Parameters are specified in parentheses. We can pass any number of arguments, but they must be separated with a comma.

Arguments are the values passed while calling a Function.

In [ ]:

def function_name(parameters):
    statement1
    statement2

Function to add two numbers :

In [3]:

#defining a Function
def add(x,y):    #x and y are Parameters
    print(x+y)

add(5,6)  #5 and 6 are Arguments.
    

While calling a function, 5 is assigned to x and 6 is assigned to y.

Default Parameters in a Function :

Default Parameters work when there are no arguments passed while calling a function. For Example :

In [4]:

#Defining a Function
def add(x=0,y=0):     #0 is the default value for x and y 
    print(x+y)

add()   #calling a Function with no arguments

Default Parameters work only when there are no arguments passed. In the code below arguments passed while calling are passed.

In [5]:

#Defining a Function
def add(x=0,y=0):     #0 is the default value for x and y 
    print(x+y)

add(7,9)   #calling the function with arguments 7 and 9

Exercise :

What will be the output of the following program?

In [ ]:

def mul(x=5,y=3,z=7):
    print(x*y*z)

    
mul(7,9)

Keyword Arguments in Python :

You can also send arguments with a key=value pair to a function. This way, you do not need to worry about the order of passing arguments. For Example:

In [3]:

def sub(x,y):
    print(x-y)


sub(y=3,x=5)

Arbitrary Arguments :

If you do not know how many arguments will be passed into your function, add a * before the parameter name in the function definition. It creates a tuple of arguments and passes it into a function. By using arbitrary arguments, we can pass any number of Arguments. For Example :

In [4]:

def add(*x):   #*x is an arbitrary argument.
    print(x)

add(5,3,3,7,8,9)  

From the above code, it is clear that an arbitrary argument creates a tuple of parameters and passes it. How can we use it to add all the values? Let's continue this code to achieve the desired result.

In [5]:

def add(*x):   #*x is an arbitrary argument.
    s = 0
    for i in x : 
        s = s+i
    
    print(f'sum of numbers is {s}')
    

add(5,3,3,7,8,9)  

You can pass almost anything in a function as an argument, like a number, a string, a list, a set, a dictionary, or even a function.

Calling a function as an argument :

In [1]:

def hello(x):
    x('hello world')

hello(print)

Types of Functions :

There are two types of functions, which are as follows:

  1. Non-Return Type Function: Non-return type functions are the functions that do not return any values. A function that does not return any values returns None. For Example :

In [2]:

def add(x,y):
    print(x+y)

value = add(5,3)
print(f'returned value to calling function is : ', value)
8
# returned value to calling function is:  None

Here, you can see add function did not return any value. It is known as a non-return type function. We have worked only on non return type Function.

Return Type Function: Return type functions are the functions that return a value. We use the keyword return to return values to the calling Function. For Example :

In [3]:

def add(x,y):
    return x+y

value = add(5,3)
print(f'returned value to calling function is : ', value)
Returned value to calling function is:  8

return multiple values to a function :

You can also return multiple values to a function by using a comma separator. It will internally create all values into a tuple and return a tuple. For Example :

In [4]:

def calc(x,y):
    return x+y , x*y , x/y , x**y

value = calc(2,2)
print(value)

As you can see, it returned a tuple of addition, multiplication, division, and exponent. But what if we want all values separated? We can use the concept of assigning multiple values to multiple variables. For Example :

In [5]:

def calc(x,y):
    return x+y , x*y , x/y , x**y

add,mul,div,exp = calc(2,2)
print(f'addition : {add}, multiplication : {mul} , division : {div} , exponent : {exp}')
addition : 4, multiplication : 4 , division : 1.0 , exponent : 4

Assignment :

1. Write a function to calculate the area and perimeter of a rectangle.

2. Write a function to calculate the area and circumference of a circle

Last updated