Python 3 – Number pow() Method
The pow() method in Python 3 is used to calculate the power of a given number. It takes two arguments, the base number and the exponent. The ‘pow()’ function returns the result of the base to the power of the exponent.
Syntax
pow(base, exponent, modulus)
Parameters
The base parameter represents the base number of the power function. The value of this parameter can be any numeric value, including integers and floating-point numbers.
The exponent parameter represents the exponent used in the power function. The value of this parameter can also be any numeric value, including integers and floating-point numbers.
The optional modulus parameter is used to calculate the modulus after calculating the power. Modulus is the remainder left over when one number is divided by another.
Return value
The returned value is the result of the base to the power of the exponent.
Let’s look at a few examples:
Example 1 – Basic Usage
a = pow(2, 3)
print(a)
Output:
8
In the example above, we have calculated the power of 2 to the exponent 3. The pow() method returns the result, which is 8.
Example 2 – Negative Exponents
a = pow(2, -3)
print(a)
Output:
0.125
In this example, we have calculated the power of 2 to the negative exponent of 3. The method pow() returns the result, which is 0.125.
Example 3 – Power with Modulus
a = pow(2, 3, 5)
print(a)
Output:
3
In this example, we have calculated the power of 2 to the exponent 3 and then calculated the modulus 5. The function ‘pow()’ returns the result, which is 3.
Example 4 – Using pow() inside a function
def power(base, exp):
return pow(base, exp)
a = power(2, 4)
print(a)
Output:
16
In this example, we have created a function ‘power()’, which takes two parameters – ‘base’ and ‘exp’. The function uses the ‘pow()’ method inside to calculate the power of the base to the exponent. Finally, the function returns the result.
We have then called the function with the base value of 2 and the exponent value of 4, which calculates and returns the result, which is 16.
Example 5 – Power of a Floating-Point Number
a = pow(2.5, 2)
print(a)
Output:
6.25
In this example, we have calculated the power of the float number 2.5 to the exponent 2. The method pow() returns the result, which is 6.25.
Conclusion
The Python 3 ‘pow()’ method is useful for calculating the power of a given number. We can easily use this method to calculate any numerical power, even with negative exponents or floating-point numbers. By understanding the different parameters that pow() takes, and how to use it inside a function, we can use pow() powerfully in our everyday coding practice.