Introduction:
This Python program calculates the result of raising a given base to a given exponent. It defines a function that accepts the base and exponent as arguments, calculates the result, and returns it. The program then prompts the user to enter the values for the base and exponent, calls the function with these values, and displays the result.
Code:
#Function to calculate and display base raised to the power exponent
#The requirements are listed below:
#1. Base and exponent are to be accepted as arguments.
#2. Calculate Baseexponent
#3. Return the result (use return statement )
#4. Display the returned value.
def calcpow(number,power): #function definition
result = 1
for i in range(1,power+1):
result = result * number
return result
base = int(input("Enter the value for the Base: "))
expo = int(input("Enter the value for the Exponent: "))
answer = calcpow(base,expo) #function call
print(base,"raised to the power",expo,"is",answer)
Logic:
- Define the function `calcpow` to calculate and return the result of base raised to the power exponent.
- Initialize the variable `result` to 1.
- Use a `for` loop to iterate from 1 to power+1.
- Inside the loop, multiply `result` by `number` and update `result`.
- Return `result`.
- Prompt the user to enter the value for the base and exponent, and store them in `base` and `expo` variables.
- Call the `calcpow` function with `base` and `expo` as arguments and store the result in the `answer` variable.
- Print the base, exponent, and the result of the calculation.
Output:
Enter the value for the Base: 2
Enter the value for the Exponent: 3
>> 2 raised to the power 3 is 8