Python: Calculate the Power of a Number Using Recursion

1. Introduction

In this blog post, we will learn how to write a Python program to calculate the power of a number using recursion.

Recursion is an effective technique in programming where a function calls itself to break down a problem into simpler sub-problems. A classic example of this technique in action is calculating the power of a number.

2. Program Overview

1. Define a recursive function to compute the power of a number.

2. Get the base and exponent values from the user.

3. Call the recursive function and display the result.

3. Code Program

# Python program to calculate the power of a number using recursion

def power(base, exponent):
    """Function to compute the power of a number using recursion."""
    # Base condition
    if exponent == 0:
        return 1
    else:
        return base * power(base, exponent - 1)

# Get base and exponent values from the user
base = float(input("Enter the base number: "))
exponent = int(input("Enter the exponent: "))

# Validate the input for exponent
if exponent < 0:
    print("Please enter a non-negative exponent.")
else:
    print(f"{base} raised to the power of {exponent} is:", power(base, exponent))

Output:

Enter the base number: 2
Enter the exponent: 3
2.0 raised to the power of 3 is: 8.0

4. Step By Step Explanation

1. We begin by defining our recursive function named power. This function will calculate the power of the base number raised to the provided exponent.

2. The base condition for our recursion is when the exponent is 0. At this point, any number raised to the power of 0 is 1.

3. If the exponent is not 0, we recursively call our function with the same base and exponent-1. We then multiply the base with the result of this recursive call. This step breaks the problem into smaller sub-problems.

4. We then prompt the user to provide the base and exponent values.

5. If the user provides a negative value for the exponent, we ask them to input a non-negative number.

6. For valid inputs, we invoke our recursive function and display the result.

Comments