Python pow Example, Power OperatorUse pow along with the power operator that has 2 stars. Pow can be used with 3 arguments to do modulo division.
In exponentiation, one number is multiplied by itself. This is performed with the pow method, a built-in. With two stars, we can also take exponents.NumbersBuilt-ins
In Python, two stars and pow are equivalent. So we can use whichever one seems clearest. I feel pow is clearer, but I rarely need exponents in programs.
Here we use pow and the exponent operator. We see that 2 squared is 4 (because 2 times 2 is four). You should know this from math class.
Here: We use both the two-star operator and the pow method. We see the results of both syntax forms are equal.
Python program that uses pow, exponents
# Two squared is four.
# ... These syntax forms are identical.
print(2 ** 2)
# Two cubed is eight.
print(2 ** 3)
Pow can be used with 3 arguments. The third argument is for modulo division. The result of the exponentiation operation is divided by that number. The remainder is returned.
Here: We take the square of 3 to get 9. And then we divide nine by five, so we have a remainder of 4.
Note: This version of pow may improve performance. But I have never needed this in a real Python program.
Python program that uses pow with 3 arguments
# Compute 3 squared.
# ... This is 9.
# ... Perform 9 modulo 5 to get result of 4.
result = pow(3, 2, 5)
A main goal of Python is syntax clarity. Python programs are easy to read and to write. With pow, we have a choice of syntax to use.
For developers who use many exponentiation operations, two stars might be clearer. But pow is often a less-common operation. For this reason it is probably a better choice overall.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.