Python Programming Notes and Practical Programs BCA 3rd Semester CSJM University Kanpur (Lecture 7) Topic- Recursion

 

Python Programming Notes and Practical Programs BCA 3rd Semester CSJM University Kanpur

 

Python Recursion

function is said to be a recursive if it calls itself. For example, lets say we have a function abc() and in the body of abc() there is a call to the abc().

Python example of Recursion

In this example we are defining a user-defined function factorial(). This function finds the factorial of a number by calling itself repeatedly until the base case(We will discuss more about base case later, after this example) is reached.

# Example of recursion in Python to

# find the factorial of a given number

 

def factorial(num):

    """This function calls itself to find

    the factorial of a number"""

 

    if num == 1:

        return 1

    else:

        return (num * factorial(num - 1))

 

 

num = 5

print("Factorial of", num, "is: ", factorial(num))

Output:

Factorial of 5 is:  120

Lets see what happens in the above example:

factorial(5) returns 5 * factorial(5-1)

    i.e. 5 * factorial(4)

               |__5*4*factorial(3)

                      |__5*4*3*factorial(2)

                           |__5*4*3*2*factorial(1)

Note: factorial(1) is a base case for which we already know the value of factorial. The base case is defined in the body of function with this code:

if num == 1:

    return 1

What is a base case in recursion

When working with recursion, we should define a base case for which we already know the answer. In the above example we are finding factorial of an integer number and we already know that the factorial of 1 is 1 so this is our base case.

Each successive recursive call to the function should bring it closer to the base case, which is exactly what we are doing in above example.

We use base case in recursive function so that the function stops calling itself when the base case is reached. Without the base case, the function would keep calling itself indefinitely.

Why use recursion in programming?

We use recursion to break a big problem in small problems and those small problems into further smaller problems and so on. At the end the solutions of all the smaller subproblems are collectively helps in finding the solution of the big main problem.

Advantages of recursion

Recursion makes our program:
1. Easier to write.
2. Readable – Code is easier to read and understand.
3. Reduce the lines of code – It takes less lines of code to solve a problem using recursion.

Disadvantages of recursion

1. Not all problems can be solved using recursion.
2. If you don’t define the base case then the code would run indefinitely.
3. Debugging is difficult in recursive functions as the function is calling itself in a
loop and it is hard to understand which call is causing the issue.
4. Memory overhead – Call to the recursive function is not memory efficient.

Python Programming Notes and Practical Programs BCA 3rd Semester CSJM University Kanpur (Lecture 6) Topic- Functions

Python Programming Notes and Practical Programs BCA 3rd Semester CSJM University Kanpur

 

Python Functions

A function is a block of code that contains one or more Python statements and used for performing a specific task.

Why use function in Python?

what we can achieve in Python by using functions in our code:
1. Code re-usability: Lets say we are writing an application in Python where we need to perform a specific task in several places of our code, assume that we need to write 10 lines of code to do that specific task. It would be better to write those 10 lines of code in a function and just call the function wherever needed, because writing those 10 lines every time you perform that task is tedious, it would make your code lengthy, less-readable and increase the chances of human errors.

2. Improves Readability: By using functions for frequent tasks you make your code structured and readable. It would be easier for anyone to look at the code and be able to understand the flow and purpose of the code.

3. Avoid redundancy: When you no longer repeat the same lines of code throughout the code and use functions in places of those, you actually avoiding the redundancy that you may have created by not using functions.

Syntax of functions in Python

Function declaration:

def function_name(function_parameters):

               function_body # Set of Python statements

        return # optional return statement

Calling the function:

# when function doesn't return anything

function_name(parameters)

OR

# when function returns something

# variable is to store the returned value

variable = function_name(parameters)

 

Python Function example

Here we have a function add() that adds two numbers passed to it as parameters. Later after function declaration we are calling the function twice in our program to perform the addition.

def add(num1, num2):

    return num1 + num2

 

 

sum1 = add(100, 200)

sum2 = add(8, 9)

print(sum1)

print(sum2)

Output:

300

17

 

Default arguments in Function

Now that we know how to declare and call a function, lets see how can we use the default arguments. By using default arguments we can avoid the errors that may arise while calling a function without passing all the parameters. Lets take an example to understand this:

In this example we have provided the default argument for the second parameter, this default argument would be used when we do not provide the second parameter while calling this function.

# default argument for second parameter

def add(num1, num2=1):

    return num1 + num2

 

 

sum1 = add(100, 200)

sum2 = add(8)  # used default argument for second param

sum3 = add(100)  # used default argument for second param

print(sum1)

print(sum2)

print(sum3)

Output:

300

9

101

 

Types of functions

There are two types of functions in Python:
1. Built-in functions: These functions are predefined in Python and we need not to declare these functions before calling them. We can freely invoke them as and when needed.
2. User defined functions: The functions which we create in our code are user-defined functions. The add() function that we have created in above examples is a user-defined function.

Topic :Software & Types, Subject: Computer Fundamental Notes for CSJM University Kanpur(for different courses like BBA, BCA, etc..)

Software Software refers to the programs, data, and instructions that enable a computer or other digital device to perform specific tasks or...