Exercise
Optimizing Local Variables In Functions
Objective
Develop a Python program with a function named "power" to compute the result of raising one integer to the power of another positive integer. The function should return an integer result. For instance, power(2, 3) should return 8.
Note: You MUST use a loop structure, such as "for" or "while", and you cannot use Math.Pow.
Example Python Exercise
Show Python Code
# Define the function to calculate the power of a number
def power(base, exponent):
result = 1 # Initialize result as 1 (since any number raised to the power of 0 is 1)
# Loop to multiply the base by itself 'exponent' times
for _ in range(exponent):
result *= base # Multiply result by the base in each iteration
return result # Return the final result
# Main function to test the power function
def main():
# Test the power function with base 2 and exponent 3
print(power(2, 3)) # Expected output: 8
# Call the main function to execute the program
main()
Output
8
Share this Python Exercise