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:
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.
- A function power is defined with two parameters:
Base Case:
- If the exponent exp is 0, the function returns 1 because any number raised to the power of 0 is 1.
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
Taking Input:
- The user is prompted to enter the base and exponent values, which are then converted to integers.
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