Blog

functions in python functions
28 Jan 2020

Functions in Python

A function is a set of one or more valid statements, which can be executed by calling the function name. As already stated, the Python program can be written within some small functions as well, so in that way, it works like a procedural language. Naturally, the question comes into our mind that why we should go for creating a function? So, below are the advantage of using the functions in Python:-

  1. A Python function implementation makes a program a more structured one. In case of debugging for an error, one does not have to scrutinize for the entire program – in case a function is not working properly he can only check the codes written within that function.
  2. A Python function helps in reducing the coding as once the code is written within a function it can be executed whenever required in the future.
  3. A Python function can be written within the same program or application or in a separate file.

 

How to Create Functions in Python?

Although there are some inbuilt functions in python few of which already we have discussed like – len(), max() some Special string functions like upper(), title() …etc. but this time we are talking about how we can create our own functions in Python which are sometimes also referred to as User Defined Function. Here we are only talking about creating a User Defined Function.

 

The following syntax can be used to define a function:

def functionname( parameters ):

[function_body]        //function body means the statements which are to be included within the function.

return [value]

 

In the above def keyword is used to define a function.

Function_body means the set of statements that are included within the function. Remember here also indentation plays an important role as it decides exactly which statements are to be considered within the python function.

The return statement is used to return some value from a function in Python if any. Remember at a particular point of time only a single value can be returned from a function.

So now think and answer if the following coding is valid or not:- 

def myfunction():

            if len(“Python Programming”) >=10:

                        return “Big”                                                  

            else :

                        return “Small”

 

A function can be of three types namely:-

  1. A Function without any parameter and returning no value.
  2. A Function with parameters but returning no value.
  3. A Function with parameters and returning value.

Now let us discuss each one with some example:-

Example:- Let us try to implement a function called greet() which will ask from the user radius of a circle and calculate the area for that circle.

 # Calculating Area of Circle

 def circlearea():

    radius=float(input(“Enter the Radius”))

    area=3.14*radius*radius

    print(“Area of Circle = %.2f” %(area))

 

#Main Coding

print(“Calclulating Area of a Circle”)

circlearea()

print(“Thanks”)

In the above coding circle area is the name of the function which has been defined by using the keyword def. It contains the statements by which it is asking radius of the circle and upon entering the radius further it calculates the area and prints the result.

However, the function is being called in the main module with the help of the statement –

Calculatearea()          and further the statements within the function is going to be executed. If you run this program the following will be the output.

Functions in Python 1

Now let us try to implement the same program by changing the function in such a way that it is able to take radius as a parameter – means the value of the radius will be supplied from outside. However, still it will not return any value.

 

# Calculating Area of Circle which takes a parameter

 def circlearea(rad):

    area=3.14*rad*rad

    print(“Area of Circle = %.2f” %(area))

  

# Main Coding

print(“Calclulating Area of a Circle”)

radius=float(input(“Enter the Radius”))

circlearea(radius)

print(“Thanks”)

 

So you must have noticed that when we are trying to call the function circle area() we are using the syntax as follows:-

circle area(radius) – here since within parenthesis we are mentioning the variable name it means we are passing the parameter to the function. 

The output screen is shown below:-

Functions in Python 2

It is up to us in which way we are going to implement a function. The parameters are also referred to as Argument. A function can take multiple no. of parameters or arguments. So it is certainly an example of Function Taking Parameters but returning no value. 

# Calculating Area of Circle which takes a parameter and returning a value

 def circlearea(rad):

    area=3.14*rad*rad

    return area 

# Main Coding 

print(“Calculating Area of a Circle”)

radius=float(input(“Enter the Radius”))

area=circlearea(radius)

print(“Area of the Circle = %.2f ” %(area))

print(“Thanks”) 

In this case, when we are calling the function circle area() we are also passing the value of the radius as a parameter within the parenthesis. However, post calculation of the circle’s area we are returning the value with the help of return statement and the value is being stored in the variable area which has been used in our main Module. So it is certainly an example of Function Taking Parameters but returning value.

Recursion in Python

Recursion is a technique by which we can call a function repeatedly from within the same function. It means a function is calling itself to execute the statements. Many programming languages like C, C++, Java …etc. support Recursion and Python is also not the exception. Here we are going to discuss how recursion can be implemented in Python. Before it is very important to know what the advantage of using Recursion is.

  • It Reduces unnecessary calling of function.
  • It reduces the time complexity of a program.

However, at the same time, it is equally true that initially, people may find it difficult to implement the concept of Recursion initially. Recursion is a technique – it is up to us whether we want to write the coding following Recursion or not. 

 

Now let us explain the things with some examples.

# Finding the factorial of a No. using Recursion.

def fact(n):

if (n ==1):

        return 1

 else :

    return n * fact(n – 1)

 

# taking input

f = int(input(‘Enter the number: \n’))

print(“Factorial = %d ” %(fact(f)))

print(“End of Program”)

 

Note: Check the statement where we have written return n * fact(n-1) –  in this function recursion is happening. Since we are calling fact() within the same function so it is a case of Recursion.

During Recursion we can have a lower limit or an upper limit here our lower limit is the line

if ( n==0) :

            return 1

So here suppose if we enter a No say 4 the execution flow will be something as given below:-

4 * fact (4 – 1)

3 * fact ( 3 – 1)

2 * fact ( 2 – 1)

1

Now each no. will be multiplied and the result will be 24. Hence 24 is the factorial of 4.

// Another Example:

// Calculate S=12+22+32+….+n2

def calculation(n1):

if (n1==1):

        return 1

 else :

        return n1*n1+calculation(n1-1)

# Main Module

n=int(input(“Enter the Value of N”))

sum=calculation(n)

print(“Total = %d ” %(sum))

 

I hope with these examples you have understood the concept of Recursion. Thus in Python, we can implement Recursion as and when required.

The output screen is shown below:-

Functions in Python 3