Power of a Number Using Recursion Understanding return in Recursion.

In this class, we write a program to find the Power of a Number Using Recursion Understanding return in Recursion.

For Complete YouTube Video: Click Here

Power of a Number Using Recursion

The reader should have prior knowledge of recursive functions execution. Click here.

Take an example and understand the question better.

Example:

Two power five will be 2*2*2*2*2. multiply 2 five times. We get the value 32.

Two power -5. The output will be 1 / 2 power 5.

Input: Given base and exponent value.

Output: Calculate base power exponent value.

This example will help you understand the return statement in recursive functions.

Logic

The function will take the base and exponent value.

Recursively call the function with a change in exponent value.

Each recursive function call reduces the exponent value by 1.

Recursively call the function if the exponent is greater than 0.

Each time multiple by base value and the value return by the function call.

Check the below program and analyze the code for better practice.

Program

def power(base,exponent):
    if exponent==0:
        return 1
    elif exponent >0:
        return base * power(base,exponent-1)
    else:
        return 1/power(base,-exponent)


base=int(input("enter the number"))
exponent=int(input("enter power of a number"))
result=power(base,exponent)
print(result)

From the above program, return base * power(base, exponent-1).

The function has to return the value base* power(base,exponent-1).

In the above line of code, the return statement is again calling the function.

The above line execution will take a base value, and it will be multiplied by the value returned by the function power(base,exponent-1).

Then the value obtained after multiplication with base is returned to the calling function.

If the exponent is negative, we are returning 1/power(base,-exponent).

For beginners, A detailed explanation of recursion execution is provided in the video.