Python pow()
Python pow() function syntax is:
1 2 3 |
pow(x, y[, z]) |
- If only two arguments are provided, then x to the power of y is returned. In this case, they can be integers, floats, and complex numbers. The two-argument form pow(x, y) is equivalent to using the power operator: x**y.
- If three arguments are provided, then x to the power y, modulo z is returned. It’s computed more efficiently than using pow(x, y) % z.
- If z is present, x and y must be of integer types, and y must be non-negative.
Let’s look into some pow() function examples.
Python pow() with integers
1 2 3 4 5 |
print(pow(10, 2)) print(pow(-10, 3)) print(pow(10, 2, 3)) |
Output:
1 2 3 4 5 |
100 -1000 1 |
Python pow() with floats
1 2 3 4 |
print(pow(100, -1)) print(pow(100.0, 2)) |
Output:
1 2 3 4 |
0.01 10000.0 |
pow() with different format integers
1 2 3 4 5 6 7 8 |
print(pow(0b11, 2)) # 0b11 = 3 print(pow(0b11, 2, 2)) print(pow(0o11, 2)) # 0o11 = 9 print(pow(0o11, 2, 2)) print(pow(0xF, 2)) # 0xF = 15 print(pow(0xF, 2, 2)) |
Output:
1 2 3 4 5 6 7 8 |
9 1 81 1 225 1 |
pow() with complex numbers
1 2 3 |
print(pow(2 + 3j, 2)) |
Output: (-5+12j)
pow() exception scenarios
-
123print(pow(2 + 3j, 2, 3))
Error:ValueError: complex modulo
-
123print(pow(100.0, 2, 3))
Error:TypeError: pow() 3rd argument not allowed unless all arguments are integers
-
123print(pow(100, -1, 2))
Error:ValueError: pow() 2nd argument cannot be negative when 3rd argument specified
pow() vs math.pow()
Python math module also has a pow() function but the built-in function is more powerful because we can perform modulo operation too after power. Also, we don’t need to import math module for a single functionality.
You can checkout complete python script and more Python examples from our GitHub Repository.
Reference: Official Documentation