How To Calculate Power In Python

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.

Let’s calculate 2 raised to the power of 3 (2^3) using pow() function:

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.

Calculating 2 raised to the power of 3 (2^3) using the ** operator:

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.

Calculating 2 raised to the power of 3 (2^3) using the custom “power” function:

Output:

8

Here’s the full code combining all three methods we’ve discussed in this tutorial:

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.