Optimizing Local Variables in Functions in Python

In this exercise, you will 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. This exercise is perfect for practicing function definition, loops, and arithmetic operations in Python. By implementing this function, you will gain hands-on experience in handling function definitions, loops, 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 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

 Copy 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

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.