Recursive Function for Calculating Power in Python

In this exercise, you will develop a Python program with a function that computes the result of raising one integer to the power of another integer (e.g., 5 raised to 3 = 5^3 = 5 × 5 × 5 = 125). This function should be implemented recursively. This exercise is perfect for practicing function definition, recursion, and arithmetic operations in Python. By implementing this function, you will gain hands-on experience in handling function definitions, recursion, and arithmetic operations in Python. This exercise not only reinforces your understanding of functions but also helps you develop efficient coding practices for managing user interactions.



Group

Mastering Functions in Python

Objective

Develop a Python program with a function that computes the result of raising one integer to the power of another integer (e.g., 5 raised to 3 = 5^3 = 5 × 5 × 5 = 125). This function should be implemented recursively.

For instance, you could use it like this: print(power(5, 3))

Example Python Exercise

 Copy Python Code
# Define the recursive function to calculate the power of a number
def power(base, exponent):
    # Base case: if the exponent is 0, the result is 1
    if exponent == 0:
        return 1
    # Recursive case: multiply base by the result of power(base, exponent-1)
    else:
        return base * power(base, exponent - 1)

# Main function to test the power function
def main():
    # Test the power function with base 5 and exponent 3
    print(power(5, 3))  # Expected output: 125

# Call the main function to execute the program
main()

 Output

125

Share this Python Exercise

More Python Programming Exercises of Mastering Functions in Python

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.