Wednesday, 4 December 2024

Day 11 : Python Program to calculate the power and exponent using recursion

 


def power(base, exp):

    if exp == 0:

        return 1

    return base * power(base, exp - 1)


base = int(input("Enter the base number: "))

exp = int(input("Enter the exponent: "))


print(power(base, exp))


This code calculates the power of a number (base) raised to an exponent (exp) using recursion. Let's break it down step-by-step:

Code Breakdown:

  1. Function Definition:

    def power(base, exp):
    • A function power is defined with two parameters:
      • base: The base number.
      • exp: The exponent to which the base number will be raised.
  2. Base Case:

    if exp == 0: return 1
    • If the exponent exp is 0, the function returns 1 because any number raised to the power of 0 is 1.
  3. Recursive Case:

    return base * power(base, exp - 1)
    • This is the key recursive step.
    • The function multiplies the base by the result of calling power(base, exp - 1).
    • It reduces the exponent by 1 each time, breaking the problem into smaller sub-problems, until exp equals 0 (base case).

    For example, if base = 2 and exp = 3, the recursion works like this:

      power(2, 3) = 2 * power(2, 2)
      power(2, 2) = 2 * power(2, 1)
      power(2, 1) = 2 * power(2, 0)
      power(2, 0) = 1 (base case)

    Then, the results are combined:

      power(2, 1) = 2 * 1 = 2
      power(2, 2) = 2 * 2 = 4
      power(2, 3) = 2 * 4 = 8
  4. Taking Input:

    base = int(input("Enter the base number: "))exp = int(input("Enter the exponent: "))
    • The user is prompted to enter the base and exponent values, which are then converted to integers.
  5. Calling the Function:

    print(power(base, exp))
    • The power function is called with the input values of base and exp, and the result is printed.

#source code --> clcoding.com


0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (76) AI (35) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (174) C (77) C# (12) C++ (82) Course (67) Coursera (231) Cybersecurity (24) data management (11) Data Science (129) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (61) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) Python (949) Python Coding Challenge (389) Python Quiz (45) Python Tips (3) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses