Calculating power is a common mathematical operation that is used to describe the product of a number when multiplied by itself a certain number of times. In this tutorial, we’ll learn how to calculate power in Python using three different methods: the built-in pow() function, the ** operator, and a custom function using a loop.
Method 1: Using the built-in pow() function
Python provides a built-in function pow() for calculating power. It takes two arguments: the base number and the exponent, and returns the power calculated as base raised to the power of the exponent.
1 |
result = pow(base, exponent) |
Let’s calculate 2 raised to the power of 3 (2^3) using pow() function:
1 2 3 4 |
base = 2 exponent = 3 result = pow(base, exponent) print(result) |
Output:
8
Method 2: Using the ** operator
Python supports a shorthand syntax for calculating power using the ** operator. This operator takes the left operand as the base and the right operand as the exponent.
1 |
result = base ** exponent |
Calculating 2 raised to the power of 3 (2^3) using the ** operator:
1 2 3 4 |
base = 2 exponent = 3 result = base ** exponent print(result) |
Output:
8
Method 3: Using a custom function with a loop
Finally, let’s create a custom function named “power” to calculate power using a loop. This function takes two arguments: the base number and the exponent, and returns the power calculated as base raised to the power of the exponent.
1 2 3 4 5 |
def power(base, exponent): result = 1 for _ in range(exponent): result *= base return result |
Calculating 2 raised to the power of 3 (2^3) using the custom “power” function:
1 2 3 4 |
base = 2 exponent = 3 result = power(base, exponent) print(result) |
Output:
8
Here’s the full code combining all three methods we’ve discussed in this tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
def power(base, exponent): result = 1 for _ in range(exponent): result *= base return result base = 2 exponent = 3 # Method 1: Using the built-in pow() function result1 = pow(base, exponent) # Method 2: Using the ** operator result2 = base ** exponent # Method 3: Using a custom function with a loop result3 = power(base, exponent) print(f'Method 1 result: {result1}') print(f'Method 2 result: {result2}') print(f'Method 3 result: {result3}') |
Output
Method 1 result: 8 Method 2 result: 8 Method 3 result: 8
Conclusion
In this tutorial, we’ve learned how to calculate power in Python using three different methods: the built-in pow() function, the ** operator, and a custom function using a loop. By understanding and using these techniques, you can easily perform power calculations in your Python programs.